package http_api

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

    "github.com/julienschmidt/httprouter"
    "github.com/nsqio/nsq/internal/app"
)

type Decorator func(APIHandler) APIHandler

type APIHandler func(http.ResponseWriter, *http.Request, httprouter.Params) (interface{}, error)

type Err struct {
    Code int
    Text string
}

func (e Err) Error() string {
    return e.Text
}

func acceptVersion(req *http.Request) int {
    if req.Header.Get("accept") == "application/vnd.nsq; version=1.0" {
        return 1
    }

    return 0
}

func PlainText(f APIHandler) APIHandler {
    return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
        code := 200
        data, err := f(w, req, ps)
        if err != nil {
            code = err.(Err).Code
            data = err.Error()
        }
        switch d := data.(type) {
        case string:
            w.WriteHeader(code)
            io.WriteString(w, d)
        case []byte:
            w.WriteHeader(code)
            w.Write(d)
        default:
            panic(fmt.Sprintf("unknown response type %T", data))
        }
        return nil, nil
    }
}

func NegotiateVersion(f APIHandler) APIHandler {
    return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
        data, err := f(w, req, ps)
        if err != nil {
            if acceptVersion(req) == 1 {
                RespondV1(w, err.(Err).Code, err)
            } else {
                // this handler always returns 500 for backwards compatibility
                Respond(w, 500, err.Error(), nil)
            }
            return nil, nil
        }
        if acceptVersion(req) == 1 {
            RespondV1(w, 200, data)
        } else {
            Respond(w, 200, "OK", data)
        }
        return nil, nil
    }
}

func V1(f APIHandler) APIHandler {
    return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
        data, err := f(w, req, ps)
        if err != nil {
            RespondV1(w, err.(Err).Code, err)
            return nil, nil
        }
        RespondV1(w, 200, data)
        return nil, nil
    }
}

func Respond(w http.ResponseWriter, statusCode int, statusTxt string, data interface{}) {
    var response []byte
    var err error

    switch data.(type) {
    case string:
        response = []byte(data.(string))
    case []byte:
        response = data.([]byte)
    default:
        w.Header().Set("Content-Type", "application/json; charset=utf-8")
        response, err = json.Marshal(struct {
            StatusCode int         `json:"status_code"`
            StatusTxt  string      `json:"status_txt"`
            Data       interface{} `json:"data"`
        }{
            statusCode,
            statusTxt,
            data,
        })
        if err != nil {
            response = []byte(fmt.Sprintf(`{"status_code":500, "status_txt":"%s", "data":null}`, err))
        }
    }

    w.WriteHeader(statusCode)
    w.Write(response)
}

func RespondV1(w http.ResponseWriter, code int, data interface{}) {
    var response []byte
    var err error
    var isJSON bool

    if code == 200 {
        switch data.(type) {
        case string:
            response = []byte(data.(string))
        case []byte:
            response = data.([]byte)
        case nil:
            response = []byte{}
        default:
            isJSON = true
            response, err = json.Marshal(data)
            if err != nil {
                code = 500
                data = err
            }
        }
    }

    if code != 200 {
        isJSON = true
        response = []byte(fmt.Sprintf(`{"message":"%s"}`, data))
    }

    if isJSON {
        w.Header().Set("Content-Type", "application/json; charset=utf-8")
    }
    w.Header().Set("X-NSQ-Content-Type", "nsq; version=1.0")
    w.WriteHeader(code)
    w.Write(response)
}

func Decorate(f APIHandler, ds ...Decorator) httprouter.Handle {
    decorated := f
    for _, decorate := range ds {
        decorated = decorate(decorated)
    }
    return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
        decorated(w, req, ps)
    }
}

func Log(l app.Logger) Decorator {
    return func(f APIHandler) APIHandler {
        return func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
            start := time.Now()
            response, err := f(w, req, ps)
            elapsed := time.Since(start)
            status := 200
            if e, ok := err.(Err); ok {
                status = e.Code
            }
            l.Output(2, fmt.Sprintf("%d %s %s (%s) %s",
                status, req.Method, req.URL.RequestURI(), req.RemoteAddr, elapsed))
            return response, err
        }
    }
}

func LogPanicHandler(l app.Logger) func(w http.ResponseWriter, req *http.Request, p interface{}) {
    return func(w http.ResponseWriter, req *http.Request, p interface{}) {
        l.Output(2, fmt.Sprintf("ERROR: panic in HTTP handler - %s", p))
        Decorate(func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
            return nil, Err{500, "INTERNAL_ERROR"}
        }, Log(l), V1)(w, req, nil)
    }
}

func LogNotFoundHandler(l app.Logger) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        Decorate(func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
            return nil, Err{404, "NOT_FOUND"}
        }, Log(l), V1)(w, req, nil)
    })
}

func LogMethodNotAllowedHandler(l app.Logger) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        Decorate(func(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (interface{}, error) {
            return nil, Err{405, "METHOD_NOT_ALLOWED"}
        }, Log(l), V1)(w, req, nil)
    })
}

api_response.go的更多相关文章

  1. NSQ之粗读浅谈

    回顾: 以前一直是C++开发(客户端),最近听同事讲go语言不错,随后便决定先从go语法开始投向go的怀抱.由于历史原因学习go语法时,用了半天的时间看完了菜鸟教程上相关资料,后来又看了易百教程上的一 ...

  2. go语言nsq源码解读八 http.go、http_server.go

    这篇讲另两个文件http.go.http_server.go,这两个文件和第六讲go语言nsq源码解读六 tcp.go.tcp_server.go里的两个文件是相对应的.那两个文件用于处理tcp请求, ...

  3. 02: djangorestframework使用

    1.1 djangorestframework登录.认证和权限 1.认证与权限相关模块 # -*- coding: utf-8 -*- from django.utils import six fro ...

  4. 用PHP编写一个APP的API

    第一部分,通信接口的实现 标签(空格分隔): PHP 手机后台 api 通信接口 Andy PHP开发手机API时,一般返回XML或JSON数据类型的数据,除了要返回从源数据(程序本身需要的数据)外还 ...

  5. 在python中配置tornado服务

    import tornado.httpserver import tornado.options import tornado.web from tornado.options import defi ...

  6. api响应类

    接口开发响应类封装 class response{ /* * 封通信接口数据 * @param integer $code 状态码 * @param string $message 状态信息 * @p ...

  7. 如何使用k3OS和Argo进行自动化边缘部署?

    本文转自边缘计算k3s社区 前 言 随着Kubernetes生态系统的发展,新的技术正在被开发出来,以实现更广泛的应用和用例.边缘计算的发展推动了对其中一些技术的需求,以实现将Kubernetes部署 ...

  8. Python+Pytest+Allure+Git+Jenkins接口自动化框架

    Python+Pytest+Allure+Git+Jenkins接口自动化框架 一.接口基础 接口测试是对系统和组件之间的接口进行测试,主要是效验数据的交换,传递和控制管理过程,以及相互逻辑依赖关系. ...

  9. 登录、认证、token处理、前台cookie存储token

    免费课程相关表设计 models的设计 from django.contrib.contenttypes.fields import GenericRelation class Course(mode ...

随机推荐

  1. javaScript(8)---对象和数组

    javaScript(8)---对象和数组 学习要点: 1.Object类型 2.Array类型 3.对象中的方法 什么是对象,其实就是一种类型,即引用类型.而对象的值就是引用类型的实例.在ECMAS ...

  2. JDBC基本使用

    J2EE技术规范(二)——JDBC 分类: java2012-12-03 14:25 1060人阅读 评论(8) 收藏 举报 一.了解JDBC (1) JDBC是以统一方式访问数据库的API (2) ...

  3. Open Source BI Platform List

    资源入口: awesome-business-intelligence https://github.com/thenaturalist/awesome-business-intelligence h ...

  4. GPU Accelerated Computing with Python

    https://developer.nvidia.com/how-to-cuda-Python python is one of the fastest growing and most popula ...

  5. SQLServer2PostgreSQL迁移过程中的几个问题

    1.PostgreSQL 跨平台迁移工具Migration Toolkit的使用指南:http://www.enterprisedb.com/docs/en/8.4/mtkguide/Table%20 ...

  6. Ionic Framework - Getting 'ionic start [appName]' Working Behind a Proxy

    This is a quick hacky way to get the ionic start [appName] command working from behind a proxy. I ra ...

  7. Ocelot中文文档-不支持

    Ocelot不支持一下几点... 分块编码 - Ocelot将始终获取body大小并返回Content-Length头. 如果这不适合你的场景,只能表示抱歉! 转发host头 - 您发给Ocelot的 ...

  8. Spark核心编程---创建RDD

    创建RDD: 1:使用程序中的集合创建RDD,主要用于进行测试,可以在实际部署到集群运行之前,自己使用集合构造测试数据,来测试后面的spark应用流程. 2:使用本地文件创建RDD,主要用于临时性地处 ...

  9. EF Linq中的左连接Left Join查询

    linq中的join是inner join内连接,就是当两个表中有一个表对应的数据没有的时候那个关联就不成立. 比如表A B的数据如下 from a in A join b in B on a.BId ...

  10. PHP $_FILES函数详解

    原创 转载请注明出处! 先来看一段代码 <form enctype="multipart/form-data" action="upload.php" m ...