Go语言建立一个最简单的服务端点

时间:2022-09-20 16:42:35

handlers/handlers.go

package handlers

import (
	"encoding/json"
	"net/http"
)

func Routes() {
	http.HandleFunc("/sendjson", SendJSON)
}

func SendJSON(rw http.ResponseWriter, r *http.Request) {
	u := struct {
		Name string
		Email string
	}{
		Name: "Bill", 
		Email: "bill@email.com",
	}
	
	rw.Header().Set("Content-Type", "application/json")
	rw.WriteHeader(200)
	json.NewEncoder(rw).Encode(&u)
}

  main.go

package main

import (
	"log"
	"net/http"
	"handlers"
)

func main() {
	handlers.Routes()
	
	log.Println("listener : Started : Listening on :4000")
	http.ListenAndServe(":4000", nil)
	
}

  Go语言建立一个最简单的服务端点