Skip to content

Instantly share code, notes, and snippets.

@x893675
Created July 22, 2020 09:22
Show Gist options
  • Save x893675/3e925ab7c82ada914cf6748752765bef to your computer and use it in GitHub Desktop.
Save x893675/3e925ab7c82ada914cf6748752765bef to your computer and use it in GitHub Desktop.
response json raw message
package main
import (
"encoding/json"
"log"
"net/http"
)
type TestJson struct {
//Str is json string
Str json.RawMessage `json:"str"`
}
func main() {
http.HandleFunc("/foo", fooHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func fooHandler(w http.ResponseWriter, r *http.Request) {
// data is json
// {
// "number": 1,
// "text": "hello"
// }
data := "{\"number\":1,\"text\":\"hello\"}"
buf := TestJson{
Str: []byte(data),
}
body, err := json.Marshal(&buf)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(body)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment