Bläddra i källkod

add json api examples

tags/v0.9.0
jimzhan 9 år sedan
förälder
incheckning
9ab009a7be
1 ändrade filer med 66 tillägg och 0 borttagningar
  1. +66
    -0
      example/main.go

+ 66
- 0
example/main.go Visa fil

@@ -1,6 +1,8 @@
package main

import (
"bytes"
"encoding/json"
"html/template"
"net/http"
"path/filepath"
@@ -23,8 +25,72 @@ func Index(w http.ResponseWriter, r *http.Request) {
}
}

type Response struct {
Code int
Text string
}

func JSON(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
next.ServeHTTP(w, r)
})
}

func fetch(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
var buffer = new(bytes.Buffer)
var response = Response{Code: http.StatusOK, Text: http.StatusText(http.StatusOK)}
if err := json.NewEncoder(buffer).Encode(response); err == nil {
w.Write(buffer.Bytes())
} else {
http.Error(w, err.Error(), http.StatusBadGateway)
}
}

func create(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
var buffer = new(bytes.Buffer)
var response = Response{Code: http.StatusCreated, Text: http.StatusText(http.StatusCreated)}
if err := json.NewEncoder(buffer).Encode(response); err == nil {
w.Write(buffer.Bytes())
} else {
http.Error(w, err.Error(), http.StatusBadGateway)
}
}

func update(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusAccepted)
var buffer = new(bytes.Buffer)
var response = Response{Code: http.StatusAccepted, Text: http.StatusText(http.StatusAccepted)}
if err := json.NewEncoder(buffer).Encode(response); err == nil {
w.Write(buffer.Bytes())
} else {
http.Error(w, err.Error(), http.StatusBadGateway)
}
}

func remove(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusGone)
var buffer = new(bytes.Buffer)
var response = Response{Code: http.StatusGone, Text: http.StatusText(http.StatusGone)}
if err := json.NewEncoder(buffer).Encode(response); err == nil {
w.Write(buffer.Bytes())
} else {
http.Error(w, err.Error(), http.StatusBadGateway)
}
}

func main() {
rex.Use(livereload.Middleware)
rex.Get("/", Index)

apis := rex.Group("/v1/")
apis.Use(JSON)
apis.Get("/", fetch)
apis.Post("/", create)
apis.Put("/", update)
apis.Delete("/", remove)

rex.Run()
}

Laddar…
Avbryt
Spara