Api.go
package core
import (
"encoding/json"
"net/http"
"os"
)
// Result νμ
μ μ
type Result struct {
Code int `json:"code"` // HTTP μν μ½λ
Data interface{} `json:"data,omitempty"` // μ νμ λ°μ΄ν°
Attr map[string]interface{} `json:"attr"` // κΈ°ν μμ±λ€
}
// HTTP μν μ½λλ€
const (
OK = 200 // μ±κ³΅
FAIL = 999 // μ€ν¨
INTERNAL_SERVER_ERROR = 500 // λ΄λΆ μλ² μ€λ₯
)
// Api ꡬ쑰체 μ μ
type Api struct{}
// Main λ©μλλ κΈ°λ³Έ λμμ μννκ³ nilμ λ°νν©λλ€.
func (api *Api) Main() interface{} {
return nil
}
// Fail λ©μλλ HTTP μλ΅μ μ€ν¨ μνλ₯Ό λ°νν©λλ€.
// κΈ°λ³Έμ μΌλ‘ μ½λ 999(FAIL)λ₯Ό λ°ννλ©°, λ©μμ§κ° μλ κ²½μ° "fail"μ κΈ°λ³Έ λ©μμ§λ‘ μ¬μ©ν©λλ€.
func (api *Api) Fail(w http.ResponseWriter, code int, msg string) {
if code == 0 {
code = FAIL
}
if msg == "" {
msg = "fail"
}
result := Result{
Code: code,
Attr: map[string]interface{}{
"msg": msg,
},
}
api.View(w, result)
}
// View λ©μλλ JSON νμμΌλ‘ HTTP μλ΅μ μ²λ¦¬ν©λλ€.
func (api *Api) View(w http.ResponseWriter, result Result) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(result.Code)
jsonResponse, err := json.Marshal(result)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(jsonResponse)
os.Exit(0) // μΌλ°μ μΌλ‘ HTTP μλ²μμλ os.Exitλ₯Ό μ¬μ©νμ§ μμ΅λλ€. μ΄ μμ μμλ κ°λ¨ν μ’
λ£λ₯Ό 보μ¬μ£ΌκΈ° μν΄ μ¬μ©νμμ΅λλ€.
}
ꡬ쑰체 μ μ
λ©μλ μ€λͺ
Last updated