server

package
v0.0.0-...-9405e43 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 27, 2019 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var HeaderApplications = [...]string{
	"",
	"application/json",
}
View Source
var HeaderLists = [...]string{
	"",
	"Content-Type",
}

Functions

func HandleCriticalError

func HandleCriticalError(err error)

func NewServer

func NewServer(config Project) error

pt-br: Monta um servidor http e deve ser montada dentro de um go runtime

Exemplo: go func(config Project){ NewServer( ... ) }(config...)

en: Mounts an http server and must be mounted within a go runtime

Example: go func(config Project){ NewServer( ... ) }(config...)

Example
package main

import (
	"encoding/json"
	"fmt"
	iotJson "github.com/helmutkemper/iotmaker.server.json"
	"io/ioutil"
	"log"
	"net/http"
	"sync"
)

func test(w http.ResponseWriter, _ *http.Request) {
	out := iotJson.NewJSonOut()
	out.Objects = []map[string]interface{}{
		{
			"string": "esta vivo",
		},
	}

	_, err := w.Write(out.Byte())
	if err != nil {
		log.Fatalf("http server error: %v", err.Error())
	}
}

func notFound(w http.ResponseWriter, _ *http.Request) {
	out := iotJson.NewJSonOut()
	out.Meta.AddError("page not found")

	_, err := w.Write(out.Byte())
	if err != nil {
		log.Fatalf("http server error: %v", err.Error())
	}
}

func testPageFound() {

	var toOut interface{}

	r, err := http.Get("http://0.0.0.0:8080/test")
	if err != nil {
		log.Fatalf("test error: %v", err.Error())
		return
	}

	fmt.Printf("status: %v\n", r.Status)
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Fatalf("test error: %v", err.Error())
		return
	}

	err = json.Unmarshal(body, &toOut)
	if err != nil {
		log.Fatalf("test error: %v", err.Error())
		return
	}

	fmt.Printf("Test page found:\n%v\n", toOut.(map[string]interface{})["Objects"])
}

func testPageNotFound() {

	var toOut interface{}

	r, err := http.Get("http://0.0.0.0:8080/notFoundPage")
	if err != nil {
		log.Fatalf("test error: %v", err.Error())
		return
	}

	fmt.Printf("status: %v\n", r.Status)
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Fatalf("test error: %v", err.Error())
		return
	}

	err = json.Unmarshal(body, &toOut)
	if err != nil {
		log.Fatalf("test error: %v", err.Error())
		return
	}

	fmt.Printf("Test page not found:\n%v\n", toOut.(map[string]interface{})["Meta"].(map[string]interface{})["Error"].([]interface{})[0])
}

func main() {

	// pt-br: configuração básica do novo servidor
	// en: basic server configuration
	var project = Project{
		ListenAndServer: ListenAndServer{
			InAddress: "0.0.0.0:8080",
		},
		DebugServerEnable: true,
		Handle: map[string]Handle{
			"/test": {
				Func: test,
				HeaderToAdd: map[HeaderList]HeaderApplication{
					KHeaderListContentType: KHeaderApplicationTypeJSon,
				},
				Method: http.MethodGet,
			},
		},
		FuncPageNotFound: notFound,
	}

	// pt-br: espera o servidor subir
	// en: wait for goes up
	var wg sync.WaitGroup
	wg.Add(1)

	// pt-br: go runtime permite que vários servidores possam existir no mesmo código apenas trocando a porta de acesso
	// en: go runtime allows multiple servers to exist in the same code just by changing the access port
	go func(project Project) {
		wg.Done()
		log.Fatalf("server error: %v", NewServer(project))
	}(project)

	wg.Wait()

	testPageFound()
	testPageNotFound()

}
Output:

status: 200 OK
Test page found:
[map[string:esta vivo]]
status: 200 OK
Test page not found:
page not found

Types

type DebugLogger

type DebugLogger struct{}

pt-br: imprime a pilha de erro caso ocorra um erro do tipo 'multiple response.WriteHeader'

en: prints the error stack if an 'multiple response.WriteHeader' type error occurs

func (DebugLogger) Write

func (d DebugLogger) Write(p []byte) (n int, err error)

type Handle

type Handle struct {
	Method              string
	Func                func(w http.ResponseWriter, r *http.Request)
	FuncOnError         func(w http.ResponseWriter, r *http.Request)
	FuncOnSecurityError func(w http.ResponseWriter, r *http.Request)
	Security            func(w http.ResponseWriter, r *http.Request) (error, bool)
	HeaderToAdd         map[HeaderList]HeaderApplication
}

type HeaderApplication

type HeaderApplication int
const (
	KHeaderApplicationTypeJSon HeaderApplication = iota + 1
)

func (HeaderApplication) String

func (el HeaderApplication) String() string

type HeaderList

type HeaderList int
const (
	KHeaderListContentType HeaderList = iota + 1
)

func (HeaderList) String

func (el HeaderList) String() string

type Listen

type Listen struct {
	InProtocol  string      `json:"inProtocol"`
	InAddress   string      `json:"inAddress"`
	OutProtocol string      `json:"outProtocol"`
	OutAddress  string      `json:"outAddress"`
	Pygocentrus pygocentrus `json:"pygocentrus"`
	// contains filtered or unexported fields
}

func (*Listen) Listen

func (el *Listen) Listen() error

type ListenAndServer

type ListenAndServer struct {
	InAddress string `json:"inAddress"`
}

type Project

type Project struct {
	Protocol    string      `yaml:"protocol"`
	Pygocentrus pygocentrus `yaml:"pygocentrus"`

	ListenAndServer     ListenAndServer `json:"listenAndServer"`
	Sll                 ssl             `json:"ssl"`
	Handle              map[string]Handle
	FuncOnError         func(w http.ResponseWriter, r *http.Request)
	FuncOnSecurityError func(w http.ResponseWriter, r *http.Request)
	FuncPageNotFound    func(w http.ResponseWriter, r *http.Request)
	Proxy               []proxy  `json:"proxy"`
	Static              []static `json:"static"`
	DebugServerEnable   bool     `json:"debugServerEnable"`
	Listen              Listen   `json:"-"`
	// contains filtered or unexported fields
}

func (*Project) HandleFunc

func (el *Project) HandleFunc(w http.ResponseWriter, r *http.Request)

func (*Project) Wait

func (el *Project) Wait()

func (*Project) WaitAddDelta

func (el *Project) WaitAddDelta()

func (*Project) WaitDone

func (el *Project) WaitDone()

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL