golanggo中的简单http服务器使用mongodb和通道(代码片段)

author author     2023-01-31     283

关键词:

package main

import (
	"encoding/json"
	"fmt"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"io"
	"math/rand"
	"net/http"
	"sync"
	"time"
)

// handler functions

// simple handler that just responds with a fixed string
func requestHandler1(w http.ResponseWriter, r *http.Request) 
	io.WriteString(w, "Hello world!")


// Handler which makes three mongo queries at the same time and responds with the 
// one that returns the quickest
func requestHandler2(w http.ResponseWriter, r *http.Request, mongoSession *mgo.Session) 
	c1 := make(chan string)
	c2 := make(chan string)
	c3 := make(chan string)

	go query("AAPL", mongoSession, c1)
	go query("GOOG", mongoSession, c2)
	go query("MSFT", mongoSession, c3)

	select 
	case data := <-c1:
		io.WriteString(w, data)
	case data := <-c2:
		io.WriteString(w, data)
	case data := <-c3:
		io.WriteString(w, data)
	



// runs a query against mongodb
func query(ticker string, mongoSession *mgo.Session, c chan string) 
	sessionCopy := mongoSession.Copy()
	defer sessionCopy.Close()
	collection := sessionCopy.DB("akka").C("stocks")
	var result bson.M
	collection.Find(bson.M"Ticker": ticker).One(&result)

	asString, _ := json.MarshalIndent(result, "", "  ")

	amt := time.Duration(rand.Intn(120))
	time.Sleep(time.Millisecond * amt)
	c <- string(asString)


// starts the application
func main() 

	server := http.Server
		Addr:    ":8000",
		Handler: NewHandler(),
	

	// start listening
	fmt.Println("Started server 2")
	server.ListenAndServe()



// Constructor for the server handlers
func NewHandler() *myHandler 
	h := new(myHandler)
	h.defineMappings()

	return h


// Definition of this struct
type myHandler struct 
	// holds the mapping
	mux map[string]func(http.ResponseWriter, *http.Request)


// functions defined on struct
func (my *myHandler) defineMappings() 

	session, err := mgo.Dial("localhost")
	if err != nil 
		panic(err)
	

	// make the mux
	my.mux = make(map[string]func(http.ResponseWriter, *http.Request))

	// matching of request path
	my.mux["/hello"] = requestHandler1
	my.mux["/get"] = my.wrap(requestHandler2, session)


// returns a function so that we can use the normal mux functionality and pass in a shared mongo session
func (my *myHandler) wrap(target func(http.ResponseWriter, *http.Request, *mgo.Session), mongoSession *mgo.Session) func(http.ResponseWriter, *http.Request) 
	return func(resp http.ResponseWriter, req *http.Request) 
		target(resp, req, mongoSession)
	


// implements serveHTTP so this struct can act as a http server
func (my *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) 
	if h, ok := my.mux[r.URL.String()]; ok 
		// handle paths that are found
		h(w, r)
		return
	 else 
		// handle unhandled paths
		io.WriteString(w, "My server: "+r.URL.String())
	

golanggo中的基本web服务器(代码片段)

查看详情

golanggo中的可附加intlist结构,它使用map作为其实现(代码片段)

查看详情

Java 中的简单 HTTP 服务器,仅使用 Java SE API

】Java中的简单HTTP服务器,仅使用JavaSEAPI【英文标题】:SimpleHTTPserverinJavausingonlyJavaSEAPI【发布时间】:2011-04-1312:36:04【问题描述】:有没有办法只使用JavaSEAPI在Java中创建一个非常基本的HTTP服务器(仅支持GET/POST),而无需编写... 查看详情

golanggo中的基本结构(代码片段)

查看详情

golanggo中的地图声明(代码片段)

查看详情

golanggo中的表驱动测试(代码片段)

查看详情

golanggo中的字符串连接(代码片段)

查看详情

golanggo中的示例列表结构支持(代码片段)

查看详情

golanggo中的格式化打印(代码片段)

查看详情

golanggo中的无限用户反馈(代码片段)

查看详情

golanggo中的样本整数struct容器(代码片段)

查看详情

golanggo中的字符串转换示例(代码片段)

查看详情

golanggo中的虚拟udp孔冲孔样本(代码片段)

查看详情

golanggo中的方法将键设置为结构(代码片段)

查看详情

golanggo(golang)中的并发安全set数据结构(代码片段)

查看详情

golanggo语言json的序列化与反序列化实践(代码片段)

Go语言JSON的序列化与反序列化实践导读本文使用Go原生支持的包,对JSON字符串以及.json文件进行序列化与反序列化实践。使用到的包是encoding/json。详细文档可查看官方中文文档,链接为:https://studygolang.com/pkgdoc本文中... 查看详情

手撸golanggo与微服务chatserver之1

...刘金亮,2021.1)本系列笔记拟采用golang练习之案例需求(聊天服务器)用户可以连接到服务器。用户可以设定自己的用户名。用户可以向服务器发送消息,同时服务器也会向其他用户广播该消息。目标定义通信协议,包括信令定义,编解... 查看详情

golanggo-sql-drivergorm数据库报错badconnection(代码片段)

...发生如下错误。"driver:badconnection"原因这是因为Mysql服务器主动关闭了Mysql链接。在项目中使用了一个mysql链接,同时使用了事务,处理多个表操作。处理时间长。导致空闲链接超时,Mysql关闭了链接。而客户端保... 查看详情