Go - Json Encoder


package main

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

)

type Response struct{
Code int `json:"Code"`
Body interface{} `json:"Body"` //"interface{}" = anyType
}

func handler(w http.ResponseWriter, r *http.Request){
//documentwrite
w.Write([]byte("<h1>Hello server</h1>")) //utf-8
fmt.Println(r.Method)//curl -X POST localhost:3000
if r.Method == http.MethodGet{
data := Response{
Code: http.StatusOK,
Body: "hi",
}
json.NewEncoder(w).Encode(data)
}
}

func main(){
//Mux
mux := http.NewServeMux()
//request , callback
mux.HandleFunc("/",handler)//指定該路徑(router)"/", registers此路徑func
//resume
http.ListenAndServe("localhost:3000",mux)
}

Comments

Popular posts from this blog

Go-VSCode -Autocomplete and Auto-import

Go - mail