text
stringlengths
11
4.05M
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 package udp import ( "bytes" "github.com/iotaledger/wasp/packages/util" "go.dedis.ch/kyber/v3" "go.dedis.ch/kyber/v3/sign/bls" ) type handshakeMsg struct { netID string // Their NetID pubKey kyber.Point // Our PubKey. respond bool // Do the message asks for a response? } func (m *handshakeMsg) bytes(secKey kyber.Scalar, suite Suite) ([]byte, error) { var err error // // Payload. var payloadBuf bytes.Buffer if err = util.WriteString16(&payloadBuf, m.netID); err != nil { return nil, err } if err = util.WriteMarshaled(&payloadBuf, m.pubKey); err != nil { return nil, err } if err = util.WriteBoolByte(&payloadBuf, m.respond); err != nil { return nil, err } var payload = payloadBuf.Bytes() var signature []byte if signature, err = bls.Sign(suite, secKey, payload); err != nil { return nil, err } // // Signed frame. var signedBuf bytes.Buffer if err = util.WriteBytes16(&signedBuf, signature); err != nil { return nil, err } if err = util.WriteBytes16(&signedBuf, payload); err != nil { return nil, err } return signedBuf.Bytes(), nil } func handshakeMsgFromBytes(buf []byte, suite Suite) (*handshakeMsg, error) { var err error // // Signed frame. rSigned := bytes.NewReader(buf) var payload []byte var signature []byte if signature, err = util.ReadBytes16(rSigned); err != nil { return nil, err } if payload, err = util.ReadBytes16(rSigned); err != nil { return nil, err } // // Payload. rPayload := bytes.NewReader(payload) m := handshakeMsg{} if m.netID, err = util.ReadString16(rPayload); err != nil { return nil, err } m.pubKey = suite.Point() if err = util.ReadMarshaled(rPayload, m.pubKey); err != nil { return nil, err } if err = util.ReadBoolByte(rPayload, &m.respond); err != nil { return nil, err } // // Verify the signature. if err = bls.Verify(suite, m.pubKey, payload, signature); err != nil { return nil, err } return &m, nil }
package main import ( "git.woa.com/trpc-go/helloworld/pkg/admin" "github.com/gorilla/mux" ) func Router(router *mux.Router, service *admin.Service) { router.HandleFunc("/", service.Status).Methods("GET") apiV1 := router.PathPrefix("/v1").Subrouter() apiV1.HandleFunc("/users/{id}", service.QueryUsers).Methods("GET").Name("helloworld.openapi.QueryUsers") }
package main import ( "fmt" "log" "runtime" "strings" "github.com/go-gl/gl/v3.3-core/gl" "github.com/go-gl/glfw/v3.2/glfw" ) const windowWidth = 512 const windowHeight = 512 func init() { // GLFW event handling must run on the main OS thread runtime.LockOSThread() } func main() { if err := glfw.Init(); err != nil { log.Fatalln("failed to initialize glfw:", err) } defer glfw.Terminate() glfw.WindowHint(glfw.Resizable, glfw.False) glfw.WindowHint(glfw.ContextVersionMajor, 3) glfw.WindowHint(glfw.ContextVersionMinor, 3) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) // glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) window, err := glfw.CreateWindow(windowWidth, windowHeight, "main", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() // Initialize Glow if err := gl.Init(); err != nil { panic(err) } version := gl.GoStr(gl.GetString(gl.VERSION)) fmt.Println("OpenGL version", version) // Configure the vertex and fragment shaders program, err := newProgram(vertexShader, fragmentShader) if err != nil { panic(err) } gl.UseProgram(program) // Configure the vertex data var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) var vbo uint32 gl.GenBuffers(1, &vbo) gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW) positionAttrib := uint32(gl.GetAttribLocation(program, gl.Str("a_position\x00"))) gl.EnableVertexAttribArray(positionAttrib) gl.VertexAttribPointer(positionAttrib, 2, gl.FLOAT, false, 0, gl.PtrOffset(0)) // Configure global settings gl.Enable(gl.DEPTH_TEST) gl.DepthFunc(gl.LESS) gl.ClearColor(1.0, 1.0, 1.0, 1.0) gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) // Render // gl.DrawArrays(gl.POINTS, 0, 3) gl.DrawArrays(gl.TRIANGLES, 0, 3) window.SwapBuffers() for !window.ShouldClose() { // Maintenance glfw.PollEvents() } } var vertices = []float32{ -0.8, -1.1, 0.0, 0.0, 1.0, -1.0, } func newProgram(vertexShaderSource, fragmentShaderSource string) (uint32, error) { vertexShader, err := compileShader(vertexShaderSource, gl.VERTEX_SHADER) if err != nil { return 0, err } fragmentShader, err := compileShader(fragmentShaderSource, gl.FRAGMENT_SHADER) if err != nil { return 0, err } program := gl.CreateProgram() gl.AttachShader(program, vertexShader) gl.AttachShader(program, fragmentShader) gl.LinkProgram(program) var status int32 gl.GetProgramiv(program, gl.LINK_STATUS, &status) if status == gl.FALSE { var logLength int32 gl.GetProgramiv(program, gl.INFO_LOG_LENGTH, &logLength) log := strings.Repeat("\x00", int(logLength+1)) gl.GetProgramInfoLog(program, logLength, nil, gl.Str(log)) return 0, fmt.Errorf("failed to link program: %v", log) } gl.DeleteShader(vertexShader) gl.DeleteShader(fragmentShader) return program, nil } func compileShader(source string, shaderType uint32) (uint32, error) { shader := gl.CreateShader(shaderType) csources, free := gl.Strs(source) gl.ShaderSource(shader, 1, csources, nil) free() gl.CompileShader(shader) var status int32 gl.GetShaderiv(shader, gl.COMPILE_STATUS, &status) if status == gl.FALSE { var logLength int32 gl.GetShaderiv(shader, gl.INFO_LOG_LENGTH, &logLength) log := strings.Repeat("\x00", int(logLength+1)) gl.GetShaderInfoLog(shader, logLength, nil, gl.Str(log)) return 0, fmt.Errorf("failed to compile %v: %v", source, log) } return shader, nil } var vertexShader = ` #version 330 attribute vec2 a_position; void main() { gl_Position = vec4(a_position, 0, 1); gl_PointSize = 20.0; } ` + "\x00" var fragmentShader = ` #version 330 void main() { gl_FragColor = vec4(1, 0, 0, 1); // red } ` + "\x00"
package main import ( "time" "github.com/zc409/gostudy/day5/mylog" ) func main() { var log1 mylog.Minelog for { //log1 = mylog.Newloger("info") //log1 = mylog.Newfileloger("info", "D:/gogo/src/github.com/zc409/gostudy/day5/homework_log/", "log.txt", 3*1024) log1 = mylog.Melog("info", "f") log1.Info("这是一个info级别的日志") log1.Warn("这是一个warn级别的日志") log1.Error("这是一个error级别的日志") log1.Fatal("这是一个fatal级别的日志") time.Sleep(2 * time.Second) } }
package goidc import ( "net/http/httptest" "testing" "time" "github.com/lyokato/goidc/authorization" "github.com/lyokato/goidc/basic_auth" "github.com/lyokato/goidc/grant" th "github.com/lyokato/goidc/test_helper" ) func TestTokenEndpointAuthorizationCodePKCE(t *testing.T) { te := NewTokenEndpoint("api.example.org") te.Support(grant.AuthorizationCode()) sdi := th.NewTestStore() user := sdi.CreateNewUser("user01", "pass01") client := sdi.CreateNewClient(user.Id, "client_id_01", "client_secret_01", "http://example.org/callback") client.AllowToUseGrantType(grant.TypeAuthorizationCode) code_verifier := "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" info, _ := sdi.CreateOrUpdateAuthInfo(user.Id, client.GetId(), "openid profile offline_access") sdi.CreateAuthSession(info, &authorization.Session{ RedirectURI: "http://example.org/callback", Code: "code_value", CodeVerifier: code_verifier, ExpiresIn: int64(60 * 60 * 24), Nonce: "07dfa90f", AuthTime: time.Now().Unix(), }) ts := httptest.NewServer(te.Handler(sdi)) defer ts.Close() // MISSING code challenge method th.TokenEndpointErrorTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/callback", "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 400, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "error": th.NewStrMatcher("invalid_request"), "error_description": th.NewStrMatcher("missing 'code_challenge_method' parameter"), }) // MISSING code challenge th.TokenEndpointErrorTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/callback", "code_challenge_method": "plain", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 400, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "error": th.NewStrMatcher("invalid_request"), "error_description": th.NewStrMatcher("missing 'code_challenge' parameter"), }) // INVALID challenge method th.TokenEndpointErrorTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/callback", "code_challenge_method": "unknown", "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 400, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "error": th.NewStrMatcher("invalid_request"), "error_description": th.NewStrMatcher("unsupported 'code_challenge_method': 'unknown'"), }) // INVALID code challenge th.TokenEndpointErrorTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/callback", "code_challenge_method": "S256", "code_challenge": "A9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 400, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "error": th.NewStrMatcher("invalid_grant"), "error_description": th.NewStrMatcher("invalid 'code_challenge': 'A9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'"), }) // VALID CODE for S256 th.TokenEndpointSuccessTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/callback", "code_challenge_method": "S256", "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 200, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "access_token": th.NewStrMatcher("ACCESS_TOKEN_0"), "refresh_token": th.NewStrMatcher("REFRESH_TOKEN_0"), "expires_in": th.NewInt64Matcher(60 * 60 * 24), }, map[string]th.Matcher{ "iss": th.NewStrMatcher("http://example.org/"), "sub": th.NewStrMatcher("0"), "aud": th.NewStrMatcher("client_id_01"), }) sdi.CreateAuthSession(info, &authorization.Session{ RedirectURI: "http://example.org/callback", Code: "code_value", CodeVerifier: code_verifier, ExpiresIn: int64(60 * 60 * 24), Nonce: "07dfa90f", AuthTime: time.Now().Unix(), }) // VALID CODE for plain th.TokenEndpointSuccessTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/callback", "code_challenge_method": "plain", "code_challenge": code_verifier, }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 200, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "access_token": th.NewStrMatcher("ACCESS_TOKEN_0"), "refresh_token": th.NewStrMatcher("REFRESH_TOKEN_0"), "expires_in": th.NewInt64Matcher(60 * 60 * 24), }, map[string]th.Matcher{ "iss": th.NewStrMatcher("http://example.org/"), "sub": th.NewStrMatcher("0"), "aud": th.NewStrMatcher("client_id_01"), }) } func TestTokenEndpointAuthorizationCodeInvalidRequest(t *testing.T) { te := NewTokenEndpoint("api.example.org") te.Support(grant.AuthorizationCode()) sdi := th.NewTestStore() user := sdi.CreateNewUser("user01", "pass01") client := sdi.CreateNewClient(user.Id, "client_id_01", "client_secret_01", "http://example.org/callback") client.AllowToUseGrantType(grant.TypeAuthorizationCode) info, _ := sdi.CreateOrUpdateAuthInfo(user.Id, client.GetId(), "openid profile offline_access") sdi.CreateAuthSession(info, &authorization.Session{ RedirectURI: "http://example.org/callback", Code: "code_value", CodeVerifier: "", ExpiresIn: int64(60 * 60 * 24), Nonce: "07dfa90f", AuthTime: time.Now().Unix(), }) ts := httptest.NewServer(te.Handler(sdi)) defer ts.Close() // MISSING REDIRECT_URI th.TokenEndpointErrorTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", //"redirect_uri": "http://example.org/callback", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 400, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "error": th.NewStrMatcher("invalid_request"), "error_description": th.NewStrMatcher("missing 'redirect_uri' parameter"), }) // INVALID REDIRECT_URI th.TokenEndpointErrorTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/invalid", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 400, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "error": th.NewStrMatcher("invalid_grant"), }) // MISSING CODE th.TokenEndpointErrorTest(t, ts, map[string]string{ "grant_type": "authorization_code", //"code": "code_value", "redirect_uri": "http://example.org/callback", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 400, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "error": th.NewStrMatcher("invalid_request"), "error_description": th.NewStrMatcher("missing 'code' parameter"), }) // INVALID CODE th.TokenEndpointErrorTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "invalid_code_value", "redirect_uri": "http://example.org/callback", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 400, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "error": th.NewStrMatcher("invalid_grant"), }) } func TestTokenEndpointAuthorizationCode(t *testing.T) { te := NewTokenEndpoint("api.example.org") te.Support(grant.AuthorizationCode()) te.AcceptClientSecret(FromAll) sdi := th.NewTestStore() user := sdi.CreateNewUser("user01", "pass01") client := sdi.CreateNewClient(user.Id, "client_id_01", "client_secret_01", "http://example.org/callback") client.AllowToUseGrantType(grant.TypeAuthorizationCode) info, _ := sdi.CreateOrUpdateAuthInfo(user.Id, client.GetId(), "openid profile offline_access") sdi.CreateAuthSession(info, &authorization.Session{ RedirectURI: "http://example.org/callback", Code: "code_value", CodeVerifier: "", ExpiresIn: int64(60 * 60 * 24), Nonce: "07dfa90f", AuthTime: time.Now().Unix(), }) ts := httptest.NewServer(te.Handler(sdi)) defer ts.Close() th.TokenEndpointSuccessTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/callback", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 200, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "access_token": th.NewStrMatcher("ACCESS_TOKEN_0"), "refresh_token": th.NewStrMatcher("REFRESH_TOKEN_0"), "expires_in": th.NewInt64Matcher(60 * 60 * 24), }, map[string]th.Matcher{ "iss": th.NewStrMatcher("http://example.org/"), "sub": th.NewStrMatcher("0"), "aud": th.NewStrMatcher("client_id_01"), }) sdi.CreateAuthSession(info, &authorization.Session{ RedirectURI: "http://example.org/callback", Code: "code_value", CodeVerifier: "", ExpiresIn: int64(60 * 60 * 24), Nonce: "07dfa90f", AuthTime: time.Now().Unix(), }) th.TokenEndpointSuccessTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/callback", "client_id": "client_id_01", "client_secret": "client_secret_01", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", }, 200, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "access_token": th.NewStrMatcher("ACCESS_TOKEN_0"), "refresh_token": th.NewStrMatcher("REFRESH_TOKEN_0"), "expires_in": th.NewInt64Matcher(60 * 60 * 24), }, map[string]th.Matcher{ "iss": th.NewStrMatcher("http://example.org/"), "sub": th.NewStrMatcher("0"), "aud": th.NewStrMatcher("client_id_01"), }) } func TestTokenEndpointAuthorizationCodeWithoutOfflineAccess(t *testing.T) { te := NewTokenEndpoint("api.example.org") te.Support(grant.AuthorizationCode()) sdi := th.NewTestStore() user := sdi.CreateNewUser("user01", "pass01") client := sdi.CreateNewClient(user.Id, "client_id_01", "client_secret_01", "http://example.org/callback") client.AllowToUseGrantType(grant.TypeAuthorizationCode) info, _ := sdi.CreateOrUpdateAuthInfo(user.Id, client.GetId(), "openid profile") sdi.CreateAuthSession(info, &authorization.Session{ RedirectURI: "http://example.org/callback", Code: "code_value", CodeVerifier: "", ExpiresIn: int64(60 * 60 * 24), Nonce: "07dfa90f", AuthTime: time.Now().Unix(), }) ts := httptest.NewServer(te.Handler(sdi)) defer ts.Close() th.TokenEndpointSuccessTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/callback", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 200, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "access_token": th.NewStrMatcher("ACCESS_TOKEN_0"), "refresh_token": th.NewAbsentMatcher(), "expires_in": th.NewInt64Matcher(60 * 60 * 24), }, map[string]th.Matcher{ "iss": th.NewStrMatcher("http://example.org/"), "sub": th.NewStrMatcher("0"), "aud": th.NewStrMatcher("client_id_01"), }) } func TestTokenEndpointAuthorizationCodeWithoutOpenID(t *testing.T) { te := NewTokenEndpoint("api.example.org") te.Support(grant.AuthorizationCode()) sdi := th.NewTestStore() user := sdi.CreateNewUser("user01", "pass01") client := sdi.CreateNewClient(user.Id, "client_id_01", "client_secret_01", "http://example.org/callback") client.AllowToUseGrantType(grant.TypeAuthorizationCode) info, _ := sdi.CreateOrUpdateAuthInfo(user.Id, client.GetId(), "profile offline_access") sdi.CreateAuthSession(info, &authorization.Session{ RedirectURI: "http://example.org/callback", Code: "code_value", CodeVerifier: "", ExpiresIn: int64(60 * 60 * 24), Nonce: "07dfa90f", AuthTime: time.Now().Unix(), }) ts := httptest.NewServer(te.Handler(sdi)) defer ts.Close() th.TokenEndpointSuccessTest(t, ts, map[string]string{ "grant_type": "authorization_code", "code": "code_value", "redirect_uri": "http://example.org/callback", }, map[string]string{ "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Authorization": basic_auth.Header("client_id_01", "client_secret_01"), }, 200, map[string]th.Matcher{ "Content-Type": th.NewStrMatcher("application/json; charset=UTF-8"), "Pragma": th.NewStrMatcher("no-cache"), "Cache-Control": th.NewStrMatcher("no-store"), }, map[string]th.Matcher{ "access_token": th.NewStrMatcher("ACCESS_TOKEN_0"), "refresh_token": th.NewStrMatcher("REFRESH_TOKEN_0"), "expires_in": th.NewInt64Matcher(60 * 60 * 24), "id_token": th.NewAbsentMatcher(), }, nil) }
package validator import ( "crypto/ecdsa" "crypto/rsa" "fmt" "net/url" "sort" "strconv" "strings" "github.com/ory/fosite" "github.com/authelia/authelia/v4/internal/configuration/schema" "github.com/authelia/authelia/v4/internal/oidc" "github.com/authelia/authelia/v4/internal/utils" ) // ValidateIdentityProviders validates and updates the IdentityProviders configuration. func ValidateIdentityProviders(config *schema.IdentityProviders, val *schema.StructValidator) { validateOIDC(config.OIDC, val) } func validateOIDC(config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { if config == nil { return } setOIDCDefaults(config) validateOIDCIssuer(config, val) validateOIDCAuthorizationPolicies(config, val) validateOIDCLifespans(config, val) sort.Sort(oidc.SortedSigningAlgs(config.Discovery.ResponseObjectSigningAlgs)) switch { case config.MinimumParameterEntropy == -1: val.PushWarning(fmt.Errorf(errFmtOIDCProviderInsecureDisabledParameterEntropy)) case config.MinimumParameterEntropy <= 0: config.MinimumParameterEntropy = fosite.MinParameterEntropy case config.MinimumParameterEntropy < fosite.MinParameterEntropy: val.PushWarning(fmt.Errorf(errFmtOIDCProviderInsecureParameterEntropy, fosite.MinParameterEntropy, config.MinimumParameterEntropy)) } switch config.EnforcePKCE { case "always", "never", "public_clients_only": break default: val.Push(fmt.Errorf(errFmtOIDCProviderEnforcePKCEInvalidValue, config.EnforcePKCE)) } validateOIDCOptionsCORS(config, val) if len(config.Clients) == 0 { val.Push(fmt.Errorf(errFmtOIDCProviderNoClientsConfigured)) } else { validateOIDCClients(config, val) } } func validateOIDCAuthorizationPolicies(config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { config.Discovery.AuthorizationPolicies = []string{policyOneFactor, policyTwoFactor} for name, policy := range config.AuthorizationPolicies { add := true switch name { case "": val.Push(fmt.Errorf(errFmtOIDCPolicyInvalidName)) add = false case policyOneFactor, policyTwoFactor, policyDeny: val.Push(fmt.Errorf(errFmtOIDCPolicyInvalidNameStandard, name, "name", strJoinAnd([]string{policyOneFactor, policyTwoFactor, policyDeny}), name)) add = false } switch policy.DefaultPolicy { case "": policy.DefaultPolicy = schema.DefaultOpenIDConnectPolicyConfiguration.DefaultPolicy case policyOneFactor, policyTwoFactor, policyDeny: break default: val.Push(fmt.Errorf(errFmtOIDCPolicyInvalidDefaultPolicy, name, strJoinAnd([]string{policyOneFactor, policyTwoFactor, policyDeny}), policy.DefaultPolicy)) } if len(policy.Rules) == 0 { val.Push(fmt.Errorf(errFmtOIDCPolicyMissingOption, name, "rules")) } for i, rule := range policy.Rules { switch rule.Policy { case "": policy.Rules[i].Policy = schema.DefaultOpenIDConnectPolicyConfiguration.DefaultPolicy case policyOneFactor, policyTwoFactor, policyDeny: break default: val.Push(fmt.Errorf(errFmtOIDCPolicyRuleInvalidPolicy, name, i+1, strJoinAnd([]string{policyOneFactor, policyTwoFactor, policyDeny}), rule.Policy)) } if len(rule.Subjects) == 0 { val.Push(fmt.Errorf(errFmtOIDCPolicyRuleMissingOption, name, i+1, "subject")) } } config.AuthorizationPolicies[name] = policy if add { config.Discovery.AuthorizationPolicies = append(config.Discovery.AuthorizationPolicies, name) } } } func validateOIDCLifespans(config *schema.IdentityProvidersOpenIDConnect, _ *schema.StructValidator) { for name := range config.Lifespans.Custom { config.Discovery.Lifespans = append(config.Discovery.Lifespans, name) } } func validateOIDCIssuer(config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { switch { case config.IssuerPrivateKey != nil: validateOIDCIssuerPrivateKey(config) fallthrough case len(config.IssuerPrivateKeys) != 0: validateOIDCIssuerPrivateKeys(config, val) default: val.Push(fmt.Errorf(errFmtOIDCProviderNoPrivateKey)) } } func validateOIDCIssuerPrivateKey(config *schema.IdentityProvidersOpenIDConnect) { config.IssuerPrivateKeys = append([]schema.JWK{{ Algorithm: oidc.SigningAlgRSAUsingSHA256, Use: oidc.KeyUseSignature, Key: config.IssuerPrivateKey, CertificateChain: config.IssuerCertificateChain, }}, config.IssuerPrivateKeys...) } func validateOIDCIssuerPrivateKeys(config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { var ( props *JWKProperties err error ) config.Discovery.ResponseObjectSigningKeyIDs = make([]string, len(config.IssuerPrivateKeys)) config.Discovery.DefaultKeyIDs = map[string]string{} for i := 0; i < len(config.IssuerPrivateKeys); i++ { if key, ok := config.IssuerPrivateKeys[i].Key.(*rsa.PrivateKey); ok && key.PublicKey.N == nil { val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysInvalid, i+1)) continue } switch n := len(config.IssuerPrivateKeys[i].KeyID); { case n == 0: if config.IssuerPrivateKeys[i].KeyID, err = jwkCalculateThumbprint(config.IssuerPrivateKeys[i].Key); err != nil { val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysCalcThumbprint, i+1, err)) continue } case n > 100: val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysKeyIDLength, i+1, config.IssuerPrivateKeys[i].KeyID)) } if config.IssuerPrivateKeys[i].KeyID != "" && utils.IsStringInSlice(config.IssuerPrivateKeys[i].KeyID, config.Discovery.ResponseObjectSigningKeyIDs) { val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysAttributeNotUnique, i+1, config.IssuerPrivateKeys[i].KeyID, attrOIDCKeyID)) } config.Discovery.ResponseObjectSigningKeyIDs[i] = config.IssuerPrivateKeys[i].KeyID if !reOpenIDConnectKID.MatchString(config.IssuerPrivateKeys[i].KeyID) { val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysKeyIDNotValid, i+1, config.IssuerPrivateKeys[i].KeyID)) } if props, err = schemaJWKGetProperties(config.IssuerPrivateKeys[i]); err != nil { val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysProperties, i+1, config.IssuerPrivateKeys[i].KeyID, err)) continue } validateOIDCIssuerPrivateKeysUseAlg(i, props, config, val) validateOIDCIssuerPrivateKeyPair(i, config, val) } if len(config.Discovery.ResponseObjectSigningAlgs) != 0 && !utils.IsStringInSlice(oidc.SigningAlgRSAUsingSHA256, config.Discovery.ResponseObjectSigningAlgs) { val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysNoRS256, oidc.SigningAlgRSAUsingSHA256, strJoinAnd(config.Discovery.ResponseObjectSigningAlgs))) } } func validateOIDCIssuerPrivateKeysUseAlg(i int, props *JWKProperties, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { switch config.IssuerPrivateKeys[i].Use { case "": config.IssuerPrivateKeys[i].Use = props.Use case oidc.KeyUseSignature: break default: val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysInvalidOptionOneOf, i+1, config.IssuerPrivateKeys[i].KeyID, attrOIDCKeyUse, strJoinOr([]string{oidc.KeyUseSignature}), config.IssuerPrivateKeys[i].Use)) } switch { case config.IssuerPrivateKeys[i].Algorithm == "": config.IssuerPrivateKeys[i].Algorithm = props.Algorithm fallthrough case utils.IsStringInSlice(config.IssuerPrivateKeys[i].Algorithm, validOIDCIssuerJWKSigningAlgs): if config.IssuerPrivateKeys[i].KeyID != "" && config.IssuerPrivateKeys[i].Algorithm != "" { if _, ok := config.Discovery.DefaultKeyIDs[config.IssuerPrivateKeys[i].Algorithm]; !ok { config.Discovery.DefaultKeyIDs[config.IssuerPrivateKeys[i].Algorithm] = config.IssuerPrivateKeys[i].KeyID } } default: val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysInvalidOptionOneOf, i+1, config.IssuerPrivateKeys[i].KeyID, attrOIDCAlgorithm, strJoinOr(validOIDCIssuerJWKSigningAlgs), config.IssuerPrivateKeys[i].Algorithm)) } if config.IssuerPrivateKeys[i].Algorithm != "" { if !utils.IsStringInSlice(config.IssuerPrivateKeys[i].Algorithm, config.Discovery.ResponseObjectSigningAlgs) { config.Discovery.ResponseObjectSigningAlgs = append(config.Discovery.ResponseObjectSigningAlgs, config.IssuerPrivateKeys[i].Algorithm) } } } func validateOIDCIssuerPrivateKeyPair(i int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { var ( checkEqualKey bool err error ) switch key := config.IssuerPrivateKeys[i].Key.(type) { case *rsa.PrivateKey: checkEqualKey = true if key.Size() < 256 { checkEqualKey = false val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysRSAKeyLessThan2048Bits, i+1, config.IssuerPrivateKeys[i].KeyID, key.Size()*8)) } case *ecdsa.PrivateKey: checkEqualKey = true default: val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysKeyNotRSAOrECDSA, i+1, config.IssuerPrivateKeys[i].KeyID, key)) } if config.IssuerPrivateKeys[i].CertificateChain.HasCertificates() { if checkEqualKey && !config.IssuerPrivateKeys[i].CertificateChain.EqualKey(config.IssuerPrivateKeys[i].Key) { val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysKeyCertificateMismatch, i+1, config.IssuerPrivateKeys[i].KeyID)) } if err = config.IssuerPrivateKeys[i].CertificateChain.Validate(); err != nil { val.Push(fmt.Errorf(errFmtOIDCProviderPrivateKeysCertificateChainInvalid, i+1, config.IssuerPrivateKeys[i].KeyID, err)) } } } func setOIDCDefaults(config *schema.IdentityProvidersOpenIDConnect) { if config.Lifespans.AccessToken == durationZero { config.Lifespans.AccessToken = schema.DefaultOpenIDConnectConfiguration.Lifespans.AccessToken } if config.Lifespans.AuthorizeCode == durationZero { config.Lifespans.AuthorizeCode = schema.DefaultOpenIDConnectConfiguration.Lifespans.AuthorizeCode } if config.Lifespans.IDToken == durationZero { config.Lifespans.IDToken = schema.DefaultOpenIDConnectConfiguration.Lifespans.IDToken } if config.Lifespans.RefreshToken == durationZero { config.Lifespans.RefreshToken = schema.DefaultOpenIDConnectConfiguration.Lifespans.RefreshToken } if config.EnforcePKCE == "" { config.EnforcePKCE = schema.DefaultOpenIDConnectConfiguration.EnforcePKCE } } func validateOIDCOptionsCORS(config *schema.IdentityProvidersOpenIDConnect, validator *schema.StructValidator) { validateOIDCOptionsCORSAllowedOrigins(config, validator) if config.CORS.AllowedOriginsFromClientRedirectURIs { validateOIDCOptionsCORSAllowedOriginsFromClientRedirectURIs(config) } validateOIDCOptionsCORSEndpoints(config, validator) } func validateOIDCOptionsCORSAllowedOrigins(config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { for _, origin := range config.CORS.AllowedOrigins { if origin.String() == "*" { if len(config.CORS.AllowedOrigins) != 1 { val.Push(fmt.Errorf(errFmtOIDCCORSInvalidOriginWildcard)) } if config.CORS.AllowedOriginsFromClientRedirectURIs { val.Push(fmt.Errorf(errFmtOIDCCORSInvalidOriginWildcardWithClients)) } continue } if origin.Path != "" { val.Push(fmt.Errorf(errFmtOIDCCORSInvalidOrigin, origin.String(), "path")) } if origin.RawQuery != "" { val.Push(fmt.Errorf(errFmtOIDCCORSInvalidOrigin, origin.String(), "query string")) } } } func validateOIDCOptionsCORSAllowedOriginsFromClientRedirectURIs(config *schema.IdentityProvidersOpenIDConnect) { for _, client := range config.Clients { for _, redirectURI := range client.RedirectURIs { uri, err := url.ParseRequestURI(redirectURI) if err != nil || (uri.Scheme != schemeHTTP && uri.Scheme != schemeHTTPS) || uri.Hostname() == "localhost" { continue } origin := utils.OriginFromURL(uri) if !utils.IsURLInSlice(*origin, config.CORS.AllowedOrigins) { config.CORS.AllowedOrigins = append(config.CORS.AllowedOrigins, *origin) } } } } func validateOIDCOptionsCORSEndpoints(config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { for _, endpoint := range config.CORS.Endpoints { if !utils.IsStringInSlice(endpoint, validOIDCCORSEndpoints) { val.Push(fmt.Errorf(errFmtOIDCCORSInvalidEndpoint, endpoint, strJoinOr(validOIDCCORSEndpoints))) } } } func validateOIDCClients(config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { var ( errDeprecated bool clientIDs, duplicateClientIDs, blankClientIDs []string ) errDeprecatedFunc := func() { errDeprecated = true } for c, client := range config.Clients { if client.ID == "" { blankClientIDs = append(blankClientIDs, "#"+strconv.Itoa(c+1)) } else { if client.Description == "" { config.Clients[c].Description = client.ID } if id := strings.ToLower(client.ID); utils.IsStringInSlice(id, clientIDs) { if !utils.IsStringInSlice(id, duplicateClientIDs) { duplicateClientIDs = append(duplicateClientIDs, id) } } else { clientIDs = append(clientIDs, id) } } validateOIDCClient(c, config, val, errDeprecatedFunc) } if errDeprecated { val.PushWarning(fmt.Errorf(errFmtOIDCClientsDeprecated)) } if len(blankClientIDs) != 0 { val.Push(fmt.Errorf(errFmtOIDCClientsWithEmptyID, buildJoinedString(", ", "or", "", blankClientIDs))) } if len(duplicateClientIDs) != 0 { val.Push(fmt.Errorf(errFmtOIDCClientsDuplicateID, strJoinOr(duplicateClientIDs))) } } func validateOIDCClient(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator, errDeprecatedFunc func()) { switch { case config.Clients[c].AuthorizationPolicy == "": config.Clients[c].AuthorizationPolicy = schema.DefaultOpenIDConnectClientConfiguration.AuthorizationPolicy case utils.IsStringInSlice(config.Clients[c].AuthorizationPolicy, config.Discovery.AuthorizationPolicies): break default: val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, "authorization_policy", strJoinOr(config.Discovery.AuthorizationPolicies), config.Clients[c].AuthorizationPolicy)) } switch { case config.Clients[c].Lifespan == "", utils.IsStringInSlice(config.Clients[c].Lifespan, config.Discovery.Lifespans): break default: if len(config.Discovery.Lifespans) == 0 { val.Push(fmt.Errorf(errFmtOIDCClientInvalidLifespan, config.Clients[c].ID, config.Clients[c].Lifespan)) } else { val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, "lifespan", strJoinOr(config.Discovery.Lifespans), config.Clients[c].Lifespan)) } } switch config.Clients[c].PKCEChallengeMethod { case "", oidc.PKCEChallengeMethodPlain, oidc.PKCEChallengeMethodSHA256: break default: val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCPKCEChallengeMethod, strJoinOr([]string{oidc.PKCEChallengeMethodPlain, oidc.PKCEChallengeMethodSHA256}), config.Clients[c].PKCEChallengeMethod)) } validateOIDCClientConsentMode(c, config, val) validateOIDCClientScopes(c, config, val, errDeprecatedFunc) validateOIDCClientResponseTypes(c, config, val, errDeprecatedFunc) validateOIDCClientResponseModes(c, config, val, errDeprecatedFunc) validateOIDCClientGrantTypes(c, config, val, errDeprecatedFunc) validateOIDCClientRedirectURIs(c, config, val, errDeprecatedFunc) validateOIDDClientSigningAlgs(c, config, val) validateOIDCClientSectorIdentifier(c, config, val) validateOIDCClientPublicKeys(c, config, val) validateOIDCClientTokenEndpointAuth(c, config, val) } func validateOIDCClientPublicKeys(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { switch { case config.Clients[c].PublicKeys.URI != nil && len(config.Clients[c].PublicKeys.Values) != 0: val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysBothURIAndValuesConfigured, config.Clients[c].ID)) case config.Clients[c].PublicKeys.URI != nil: if config.Clients[c].PublicKeys.URI.Scheme != schemeHTTPS { val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysURIInvalidScheme, config.Clients[c].ID, config.Clients[c].PublicKeys.URI.Scheme)) } case len(config.Clients[c].PublicKeys.Values) != 0: validateOIDCClientJSONWebKeysList(c, config, val) } } func validateOIDCClientJSONWebKeysList(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { var ( props *JWKProperties err error ) for i := 0; i < len(config.Clients[c].PublicKeys.Values); i++ { if config.Clients[c].PublicKeys.Values[i].KeyID == "" { val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysInvalidOptionMissingOneOf, config.Clients[c].ID, i+1, attrOIDCKeyID)) } if props, err = schemaJWKGetProperties(config.Clients[c].PublicKeys.Values[i]); err != nil { val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysProperties, config.Clients[c].ID, i+1, config.Clients[c].PublicKeys.Values[i].KeyID, err)) continue } validateOIDCClientJSONWebKeysListKeyUseAlg(c, i, props, config, val) var checkEqualKey bool switch key := config.Clients[c].PublicKeys.Values[i].Key.(type) { case nil: val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysInvalidOptionMissingOneOf, config.Clients[c].ID, i+1, attrOIDCKey)) case *rsa.PublicKey: checkEqualKey = true if key.N == nil { checkEqualKey = false val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysKeyMalformed, config.Clients[c].ID, i+1)) } else if key.Size() < 256 { checkEqualKey = false val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysRSAKeyLessThan2048Bits, config.Clients[c].ID, i+1, config.Clients[c].PublicKeys.Values[i].KeyID, key.Size()*8)) } case *ecdsa.PublicKey: checkEqualKey = true default: val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysKeyNotRSAOrECDSA, config.Clients[c].ID, i+1, config.Clients[c].PublicKeys.Values[i].KeyID, key)) } if config.Clients[c].PublicKeys.Values[i].CertificateChain.HasCertificates() { if checkEqualKey && !config.Clients[c].PublicKeys.Values[i].CertificateChain.EqualKey(config.Clients[c].PublicKeys.Values[i].Key) { val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysCertificateChainKeyMismatch, config.Clients[c].ID, i+1, config.Clients[c].PublicKeys.Values[i].KeyID)) } if err = config.Clients[c].PublicKeys.Values[i].CertificateChain.Validate(); err != nil { val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysCertificateChainInvalid, config.Clients[c].ID, i+1, config.Clients[c].PublicKeys.Values[i].KeyID, err)) } } } if config.Clients[c].RequestObjectSigningAlg != "" && !utils.IsStringInSlice(config.Clients[c].RequestObjectSigningAlg, config.Clients[c].Discovery.RequestObjectSigningAlgs) { val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysROSAMissingAlgorithm, config.Clients[c].ID, strJoinOr(config.Clients[c].Discovery.RequestObjectSigningAlgs))) } } func validateOIDCClientJSONWebKeysListKeyUseAlg(c, i int, props *JWKProperties, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { switch config.Clients[c].PublicKeys.Values[i].Use { case "": config.Clients[c].PublicKeys.Values[i].Use = props.Use case oidc.KeyUseSignature: break default: val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysInvalidOptionOneOf, config.Clients[c].ID, i+1, config.Clients[c].PublicKeys.Values[i].KeyID, attrOIDCKeyUse, strJoinOr([]string{oidc.KeyUseSignature}), config.Clients[c].PublicKeys.Values[i].Use)) } switch { case config.Clients[c].PublicKeys.Values[i].Algorithm == "": config.Clients[c].PublicKeys.Values[i].Algorithm = props.Algorithm case utils.IsStringInSlice(config.Clients[c].PublicKeys.Values[i].Algorithm, validOIDCIssuerJWKSigningAlgs): break default: val.Push(fmt.Errorf(errFmtOIDCClientPublicKeysInvalidOptionOneOf, config.Clients[c].ID, i+1, config.Clients[c].PublicKeys.Values[i].KeyID, attrOIDCAlgorithm, strJoinOr(validOIDCIssuerJWKSigningAlgs), config.Clients[c].PublicKeys.Values[i].Algorithm)) } if config.Clients[c].PublicKeys.Values[i].Algorithm != "" { if !utils.IsStringInSlice(config.Clients[c].PublicKeys.Values[i].Algorithm, config.Discovery.RequestObjectSigningAlgs) { config.Discovery.RequestObjectSigningAlgs = append(config.Discovery.RequestObjectSigningAlgs, config.Clients[c].PublicKeys.Values[i].Algorithm) } if !utils.IsStringInSlice(config.Clients[c].PublicKeys.Values[i].Algorithm, config.Clients[c].Discovery.RequestObjectSigningAlgs) { config.Clients[c].Discovery.RequestObjectSigningAlgs = append(config.Clients[c].Discovery.RequestObjectSigningAlgs, config.Clients[c].PublicKeys.Values[i].Algorithm) } } } func validateOIDCClientSectorIdentifier(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { if config.Clients[c].SectorIdentifier.String() != "" { if utils.IsURLHostComponent(config.Clients[c].SectorIdentifier) || utils.IsURLHostComponentWithPort(config.Clients[c].SectorIdentifier) { return } if config.Clients[c].SectorIdentifier.Scheme != "" { val.Push(fmt.Errorf(errFmtOIDCClientInvalidSectorIdentifier, config.Clients[c].ID, config.Clients[c].SectorIdentifier.String(), config.Clients[c].SectorIdentifier.Host, "scheme", config.Clients[c].SectorIdentifier.Scheme)) if config.Clients[c].SectorIdentifier.Path != "" { val.Push(fmt.Errorf(errFmtOIDCClientInvalidSectorIdentifier, config.Clients[c].ID, config.Clients[c].SectorIdentifier.String(), config.Clients[c].SectorIdentifier.Host, "path", config.Clients[c].SectorIdentifier.Path)) } if config.Clients[c].SectorIdentifier.RawQuery != "" { val.Push(fmt.Errorf(errFmtOIDCClientInvalidSectorIdentifier, config.Clients[c].ID, config.Clients[c].SectorIdentifier.String(), config.Clients[c].SectorIdentifier.Host, "query", config.Clients[c].SectorIdentifier.RawQuery)) } if config.Clients[c].SectorIdentifier.Fragment != "" { val.Push(fmt.Errorf(errFmtOIDCClientInvalidSectorIdentifier, config.Clients[c].ID, config.Clients[c].SectorIdentifier.String(), config.Clients[c].SectorIdentifier.Host, "fragment", config.Clients[c].SectorIdentifier.Fragment)) } if config.Clients[c].SectorIdentifier.User != nil { if config.Clients[c].SectorIdentifier.User.Username() != "" { val.Push(fmt.Errorf(errFmtOIDCClientInvalidSectorIdentifier, config.Clients[c].ID, config.Clients[c].SectorIdentifier.String(), config.Clients[c].SectorIdentifier.Host, "username", config.Clients[c].SectorIdentifier.User.Username())) } if _, set := config.Clients[c].SectorIdentifier.User.Password(); set { val.Push(fmt.Errorf(errFmtOIDCClientInvalidSectorIdentifierWithoutValue, config.Clients[c].ID, config.Clients[c].SectorIdentifier.String(), config.Clients[c].SectorIdentifier.Host, "password")) } } } else if config.Clients[c].SectorIdentifier.Host == "" { val.Push(fmt.Errorf(errFmtOIDCClientInvalidSectorIdentifierHost, config.Clients[c].ID, config.Clients[c].SectorIdentifier.String())) } } } func validateOIDCClientConsentMode(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { switch { case utils.IsStringInSlice(config.Clients[c].ConsentMode, []string{"", auto}): if config.Clients[c].ConsentPreConfiguredDuration != nil { config.Clients[c].ConsentMode = oidc.ClientConsentModePreConfigured.String() } else { config.Clients[c].ConsentMode = oidc.ClientConsentModeExplicit.String() } case utils.IsStringInSlice(config.Clients[c].ConsentMode, validOIDCClientConsentModes): break default: val.Push(fmt.Errorf(errFmtOIDCClientInvalidConsentMode, config.Clients[c].ID, strJoinOr(append(validOIDCClientConsentModes, auto)), config.Clients[c].ConsentMode)) } if config.Clients[c].ConsentMode == oidc.ClientConsentModePreConfigured.String() && config.Clients[c].ConsentPreConfiguredDuration == nil { config.Clients[c].ConsentPreConfiguredDuration = schema.DefaultOpenIDConnectClientConfiguration.ConsentPreConfiguredDuration } } func validateOIDCClientScopes(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator, errDeprecatedFunc func()) { if len(config.Clients[c].Scopes) == 0 { config.Clients[c].Scopes = schema.DefaultOpenIDConnectClientConfiguration.Scopes } invalid, duplicates := validateList(config.Clients[c].Scopes, validOIDCClientScopes, true) if len(duplicates) != 0 { errDeprecatedFunc() val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidEntryDuplicates, config.Clients[c].ID, attrOIDCScopes, strJoinAnd(duplicates))) } if utils.IsStringInSlice(oidc.GrantTypeClientCredentials, config.Clients[c].GrantTypes) { validateOIDCClientScopesClientCredentialsGrant(c, config, val) } else { if !utils.IsStringInSlice(oidc.ScopeOpenID, config.Clients[c].Scopes) { config.Clients[c].Scopes = append([]string{oidc.ScopeOpenID}, config.Clients[c].Scopes...) } if len(invalid) != 0 { val.Push(fmt.Errorf(errFmtOIDCClientInvalidEntries, config.Clients[c].ID, attrOIDCScopes, strJoinOr(validOIDCClientScopes), strJoinAnd(invalid))) } } if utils.IsStringSliceContainsAny([]string{oidc.ScopeOfflineAccess, oidc.ScopeOffline}, config.Clients[c].Scopes) && !utils.IsStringSliceContainsAny(validOIDCClientResponseTypesRefreshToken, config.Clients[c].ResponseTypes) { errDeprecatedFunc() val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidRefreshTokenOptionWithoutCodeResponseType, config.Clients[c].ID, attrOIDCScopes, strJoinOr([]string{oidc.ScopeOfflineAccess, oidc.ScopeOffline}), strJoinOr(validOIDCClientResponseTypesRefreshToken)), ) } } func validateOIDCClientScopesClientCredentialsGrant(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { if len(config.Clients[c].GrantTypes) != 1 { return } invalid := validateListNotAllowed(config.Clients[c].Scopes, []string{oidc.ScopeOpenID, oidc.ScopeOffline, oidc.ScopeOfflineAccess}) if len(invalid) > 0 { val.Push(fmt.Errorf(errFmtOIDCClientInvalidEntriesClientCredentials, config.Clients[c].ID, strJoinAnd(config.Clients[c].Scopes), strJoinOr(invalid))) } } func validateOIDCClientResponseTypes(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator, errDeprecatedFunc func()) { if len(config.Clients[c].ResponseTypes) == 0 { config.Clients[c].ResponseTypes = schema.DefaultOpenIDConnectClientConfiguration.ResponseTypes } invalid, duplicates := validateList(config.Clients[c].ResponseTypes, validOIDCClientResponseTypes, true) if len(invalid) != 0 { val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidEntries, config.Clients[c].ID, attrOIDCResponseTypes, strJoinOr(validOIDCClientResponseTypes), strJoinAnd(invalid))) } if len(duplicates) != 0 { errDeprecatedFunc() val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidEntryDuplicates, config.Clients[c].ID, attrOIDCResponseTypes, strJoinAnd(duplicates))) } } func validateOIDCClientResponseModes(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator, errDeprecatedFunc func()) { if len(config.Clients[c].ResponseModes) == 0 { config.Clients[c].ResponseModes = schema.DefaultOpenIDConnectClientConfiguration.ResponseModes for _, responseType := range config.Clients[c].ResponseTypes { switch responseType { case oidc.ResponseTypeAuthorizationCodeFlow: if !utils.IsStringInSlice(oidc.ResponseModeQuery, config.Clients[c].ResponseModes) { config.Clients[c].ResponseModes = append(config.Clients[c].ResponseModes, oidc.ResponseModeQuery) } case oidc.ResponseTypeImplicitFlowIDToken, oidc.ResponseTypeImplicitFlowToken, oidc.ResponseTypeImplicitFlowBoth, oidc.ResponseTypeHybridFlowIDToken, oidc.ResponseTypeHybridFlowToken, oidc.ResponseTypeHybridFlowBoth: if !utils.IsStringInSlice(oidc.ResponseModeFragment, config.Clients[c].ResponseModes) { config.Clients[c].ResponseModes = append(config.Clients[c].ResponseModes, oidc.ResponseModeFragment) } } } } invalid, duplicates := validateList(config.Clients[c].ResponseModes, validOIDCClientResponseModes, true) if len(invalid) != 0 { val.Push(fmt.Errorf(errFmtOIDCClientInvalidEntries, config.Clients[c].ID, attrOIDCResponseModes, strJoinOr(validOIDCClientResponseModes), strJoinAnd(invalid))) } if len(duplicates) != 0 { errDeprecatedFunc() val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidEntryDuplicates, config.Clients[c].ID, attrOIDCResponseModes, strJoinAnd(duplicates))) } } func validateOIDCClientGrantTypes(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator, errDeprecatedFunc func()) { if len(config.Clients[c].GrantTypes) == 0 { validateOIDCClientGrantTypesSetDefaults(c, config) } validateOIDCClientGrantTypesCheckRelated(c, config, val, errDeprecatedFunc) invalid, duplicates := validateList(config.Clients[c].GrantTypes, validOIDCClientGrantTypes, true) if len(invalid) != 0 { val.Push(fmt.Errorf(errFmtOIDCClientInvalidEntries, config.Clients[c].ID, attrOIDCGrantTypes, strJoinOr(validOIDCClientGrantTypes), strJoinAnd(invalid))) } if len(duplicates) != 0 { errDeprecatedFunc() val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidEntryDuplicates, config.Clients[c].ID, attrOIDCGrantTypes, strJoinAnd(duplicates))) } } func validateOIDCClientGrantTypesSetDefaults(c int, config *schema.IdentityProvidersOpenIDConnect) { for _, responseType := range config.Clients[c].ResponseTypes { switch responseType { case oidc.ResponseTypeAuthorizationCodeFlow: if !utils.IsStringInSlice(oidc.GrantTypeAuthorizationCode, config.Clients[c].GrantTypes) { config.Clients[c].GrantTypes = append(config.Clients[c].GrantTypes, oidc.GrantTypeAuthorizationCode) } case oidc.ResponseTypeImplicitFlowIDToken, oidc.ResponseTypeImplicitFlowToken, oidc.ResponseTypeImplicitFlowBoth: if !utils.IsStringInSlice(oidc.GrantTypeImplicit, config.Clients[c].GrantTypes) { config.Clients[c].GrantTypes = append(config.Clients[c].GrantTypes, oidc.GrantTypeImplicit) } case oidc.ResponseTypeHybridFlowIDToken, oidc.ResponseTypeHybridFlowToken, oidc.ResponseTypeHybridFlowBoth: if !utils.IsStringInSlice(oidc.GrantTypeAuthorizationCode, config.Clients[c].GrantTypes) { config.Clients[c].GrantTypes = append(config.Clients[c].GrantTypes, oidc.GrantTypeAuthorizationCode) } if !utils.IsStringInSlice(oidc.GrantTypeImplicit, config.Clients[c].GrantTypes) { config.Clients[c].GrantTypes = append(config.Clients[c].GrantTypes, oidc.GrantTypeImplicit) } } } } func validateOIDCClientGrantTypesCheckRelated(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator, errDeprecatedFunc func()) { for _, grantType := range config.Clients[c].GrantTypes { switch grantType { case oidc.GrantTypeAuthorizationCode: if !utils.IsStringInSlice(oidc.ResponseTypeAuthorizationCodeFlow, config.Clients[c].ResponseTypes) && !utils.IsStringSliceContainsAny(validOIDCClientResponseTypesHybridFlow, config.Clients[c].ResponseTypes) { errDeprecatedFunc() val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidGrantTypeMatch, config.Clients[c].ID, grantType, "for either the authorization code or hybrid flow", strJoinOr(append([]string{oidc.ResponseTypeAuthorizationCodeFlow}, validOIDCClientResponseTypesHybridFlow...)), strJoinAnd(config.Clients[c].ResponseTypes))) } case oidc.GrantTypeImplicit: if !utils.IsStringSliceContainsAny(validOIDCClientResponseTypesImplicitFlow, config.Clients[c].ResponseTypes) && !utils.IsStringSliceContainsAny(validOIDCClientResponseTypesHybridFlow, config.Clients[c].ResponseTypes) { errDeprecatedFunc() val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidGrantTypeMatch, config.Clients[c].ID, grantType, "for either the implicit or hybrid flow", strJoinOr(append(append([]string{}, validOIDCClientResponseTypesImplicitFlow...), validOIDCClientResponseTypesHybridFlow...)), strJoinAnd(config.Clients[c].ResponseTypes))) } case oidc.GrantTypeClientCredentials: if config.Clients[c].Public { val.Push(fmt.Errorf(errFmtOIDCClientInvalidGrantTypePublic, config.Clients[c].ID, oidc.GrantTypeClientCredentials)) } case oidc.GrantTypeRefreshToken: if !utils.IsStringSliceContainsAny([]string{oidc.ScopeOfflineAccess, oidc.ScopeOffline}, config.Clients[c].Scopes) { errDeprecatedFunc() val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidGrantTypeRefresh, config.Clients[c].ID)) } if !utils.IsStringSliceContainsAny(validOIDCClientResponseTypesRefreshToken, config.Clients[c].ResponseTypes) { errDeprecatedFunc() val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidRefreshTokenOptionWithoutCodeResponseType, config.Clients[c].ID, attrOIDCGrantTypes, strJoinOr([]string{oidc.GrantTypeRefreshToken}), strJoinOr(validOIDCClientResponseTypesRefreshToken)), ) } } } } func validateOIDCClientRedirectURIs(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator, errDeprecatedFunc func()) { var ( parsedRedirectURI *url.URL err error ) for _, redirectURI := range config.Clients[c].RedirectURIs { if redirectURI == oauth2InstalledApp { if config.Clients[c].Public { continue } val.Push(fmt.Errorf(errFmtOIDCClientRedirectURIPublic, config.Clients[c].ID, oauth2InstalledApp)) continue } if parsedRedirectURI, err = url.Parse(redirectURI); err != nil { val.Push(fmt.Errorf(errFmtOIDCClientRedirectURICantBeParsed, config.Clients[c].ID, redirectURI, err)) continue } if !parsedRedirectURI.IsAbs() || (!config.Clients[c].Public && parsedRedirectURI.Scheme == "") { val.Push(fmt.Errorf(errFmtOIDCClientRedirectURIAbsolute, config.Clients[c].ID, redirectURI)) } } _, duplicates := validateList(config.Clients[c].RedirectURIs, nil, true) if len(duplicates) != 0 { errDeprecatedFunc() val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidEntryDuplicates, config.Clients[c].ID, attrOIDCRedirectURIs, strJoinAnd(duplicates))) } } //nolint:gocyclo func validateOIDCClientTokenEndpointAuth(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { implicit := len(config.Clients[c].ResponseTypes) != 0 && utils.IsStringSliceContainsAll(config.Clients[c].ResponseTypes, validOIDCClientResponseTypesImplicitFlow) switch { case config.Clients[c].TokenEndpointAuthMethod == "": break case !utils.IsStringInSlice(config.Clients[c].TokenEndpointAuthMethod, validOIDCClientTokenEndpointAuthMethods): val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCTokenAuthMethod, strJoinOr(validOIDCClientTokenEndpointAuthMethods), config.Clients[c].TokenEndpointAuthMethod)) return case config.Clients[c].TokenEndpointAuthMethod == oidc.ClientAuthMethodNone && !config.Clients[c].Public && !implicit: val.Push(fmt.Errorf(errFmtOIDCClientInvalidTokenEndpointAuthMethod, config.Clients[c].ID, strJoinOr(validOIDCClientTokenEndpointAuthMethodsConfidential), strJoinAnd(validOIDCClientResponseTypesImplicitFlow), config.Clients[c].TokenEndpointAuthMethod)) case config.Clients[c].TokenEndpointAuthMethod != oidc.ClientAuthMethodNone && config.Clients[c].Public: val.Push(fmt.Errorf(errFmtOIDCClientInvalidTokenEndpointAuthMethodPublic, config.Clients[c].ID, config.Clients[c].TokenEndpointAuthMethod)) } secret := false switch config.Clients[c].TokenEndpointAuthMethod { case oidc.ClientAuthMethodClientSecretJWT: validateOIDCClientTokenEndpointAuthClientSecretJWT(c, config, val) secret = true case "": if !config.Clients[c].Public { secret = true } case oidc.ClientAuthMethodClientSecretPost, oidc.ClientAuthMethodClientSecretBasic: secret = true case oidc.ClientAuthMethodPrivateKeyJWT: validateOIDCClientTokenEndpointAuthPublicKeyJWT(config.Clients[c], val) } if secret { if config.Clients[c].Public { return } if config.Clients[c].Secret == nil { val.Push(fmt.Errorf(errFmtOIDCClientInvalidSecret, config.Clients[c].ID)) } else { switch { case config.Clients[c].Secret.IsPlainText() && config.Clients[c].TokenEndpointAuthMethod != oidc.ClientAuthMethodClientSecretJWT: val.PushWarning(fmt.Errorf(errFmtOIDCClientInvalidSecretPlainText, config.Clients[c].ID)) case !config.Clients[c].Secret.IsPlainText() && config.Clients[c].TokenEndpointAuthMethod == oidc.ClientAuthMethodClientSecretJWT: val.Push(fmt.Errorf(errFmtOIDCClientInvalidSecretNotPlainText, config.Clients[c].ID)) } } } else if config.Clients[c].Secret != nil { if config.Clients[c].Public { val.Push(fmt.Errorf(errFmtOIDCClientPublicInvalidSecret, config.Clients[c].ID)) } else { val.Push(fmt.Errorf(errFmtOIDCClientPublicInvalidSecretClientAuthMethod, config.Clients[c].ID, config.Clients[c].TokenEndpointAuthMethod)) } } } func validateOIDCClientTokenEndpointAuthClientSecretJWT(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { switch { case config.Clients[c].TokenEndpointAuthSigningAlg == "": config.Clients[c].TokenEndpointAuthSigningAlg = oidc.SigningAlgHMACUsingSHA256 case !utils.IsStringInSlice(config.Clients[c].TokenEndpointAuthSigningAlg, validOIDCClientTokenEndpointAuthSigAlgsClientSecretJWT): val.Push(fmt.Errorf(errFmtOIDCClientInvalidTokenEndpointAuthSigAlg, config.Clients[c].ID, strJoinOr(validOIDCClientTokenEndpointAuthSigAlgsClientSecretJWT), config.Clients[c].TokenEndpointAuthMethod)) } } func validateOIDCClientTokenEndpointAuthPublicKeyJWT(config schema.IdentityProvidersOpenIDConnectClient, val *schema.StructValidator) { switch { case config.TokenEndpointAuthSigningAlg == "": val.Push(fmt.Errorf(errFmtOIDCClientInvalidTokenEndpointAuthSigAlgMissingPrivateKeyJWT, config.ID)) case !utils.IsStringInSlice(config.TokenEndpointAuthSigningAlg, validOIDCIssuerJWKSigningAlgs): val.Push(fmt.Errorf(errFmtOIDCClientInvalidTokenEndpointAuthSigAlg, config.ID, strJoinOr(validOIDCIssuerJWKSigningAlgs), config.TokenEndpointAuthMethod)) } if config.PublicKeys.URI == nil { if len(config.PublicKeys.Values) == 0 { val.Push(fmt.Errorf(errFmtOIDCClientInvalidPublicKeysPrivateKeyJWT, config.ID)) } else if len(config.Discovery.RequestObjectSigningAlgs) != 0 && !utils.IsStringInSlice(config.TokenEndpointAuthSigningAlg, config.Discovery.RequestObjectSigningAlgs) { val.Push(fmt.Errorf(errFmtOIDCClientInvalidTokenEndpointAuthSigAlgReg, config.ID, strJoinOr(config.Discovery.RequestObjectSigningAlgs), config.TokenEndpointAuthMethod)) } } } func validateOIDDClientSigningAlgs(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { validateOIDDClientSigningAlgsJARM(c, config, val) validateOIDDClientSigningAlgsIDToken(c, config, val) validateOIDDClientSigningAlgsAccessToken(c, config, val) validateOIDDClientSigningAlgsUserInfo(c, config, val) validateOIDDClientSigningAlgsIntrospection(c, config, val) } func validateOIDDClientSigningAlgsIDToken(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { config.Clients[c].IDTokenSignedResponseAlg, config.Clients[c].IDTokenSignedResponseKeyID = validateOIDCClientAlgKIDDefault(config, config.Clients[c].IDTokenSignedResponseAlg, config.Clients[c].IDTokenSignedResponseKeyID, schema.DefaultOpenIDConnectClientConfiguration.IDTokenSignedResponseAlg) switch config.Clients[c].IDTokenSignedResponseKeyID { case "": switch config.Clients[c].IDTokenSignedResponseAlg { case "", oidc.SigningAlgRSAUsingSHA256: break default: if !utils.IsStringInSlice(config.Clients[c].IDTokenSignedResponseAlg, config.Discovery.ResponseObjectSigningAlgs) { val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCIDTokenSigAlg, strJoinOr(config.Discovery.ResponseObjectSigningAlgs), config.Clients[c].IDTokenSignedResponseAlg)) } } default: if !utils.IsStringInSlice(config.Clients[c].IDTokenSignedResponseKeyID, config.Discovery.ResponseObjectSigningKeyIDs) { val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCIDTokenSigKID, strJoinOr(config.Discovery.ResponseObjectSigningKeyIDs), config.Clients[c].IDTokenSignedResponseKeyID)) } else { config.Clients[c].IDTokenSignedResponseAlg = getResponseObjectAlgFromKID(config, config.Clients[c].IDTokenSignedResponseKeyID, config.Clients[c].IDTokenSignedResponseAlg) } } } func validateOIDDClientSigningAlgsAccessToken(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { config.Clients[c].AccessTokenSignedResponseAlg, config.Clients[c].AccessTokenSignedResponseKeyID = validateOIDCClientAlgKIDDefault(config, config.Clients[c].AccessTokenSignedResponseAlg, config.Clients[c].AccessTokenSignedResponseKeyID, schema.DefaultOpenIDConnectClientConfiguration.AccessTokenSignedResponseAlg) switch config.Clients[c].AccessTokenSignedResponseKeyID { case "": switch config.Clients[c].AccessTokenSignedResponseAlg { case "", oidc.SigningAlgNone, oidc.SigningAlgRSAUsingSHA256: break default: if !utils.IsStringInSlice(config.Clients[c].AccessTokenSignedResponseAlg, config.Discovery.ResponseObjectSigningAlgs) { val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCAccessTokenSigAlg, strJoinOr(config.Discovery.ResponseObjectSigningAlgs), config.Clients[c].AccessTokenSignedResponseAlg)) } else { config.Discovery.JWTResponseAccessTokens = true } } default: switch { case !utils.IsStringInSlice(config.Clients[c].AccessTokenSignedResponseKeyID, config.Discovery.ResponseObjectSigningKeyIDs): val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCAccessTokenSigKID, strJoinOr(config.Discovery.ResponseObjectSigningKeyIDs), config.Clients[c].AccessTokenSignedResponseKeyID)) default: config.Clients[c].AccessTokenSignedResponseAlg = getResponseObjectAlgFromKID(config, config.Clients[c].AccessTokenSignedResponseKeyID, config.Clients[c].AccessTokenSignedResponseAlg) config.Discovery.JWTResponseAccessTokens = true } } } func validateOIDDClientSigningAlgsUserInfo(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { config.Clients[c].UserinfoSignedResponseAlg, config.Clients[c].UserinfoSignedResponseKeyID = validateOIDCClientAlgKIDDefault(config, config.Clients[c].UserinfoSignedResponseAlg, config.Clients[c].UserinfoSignedResponseKeyID, schema.DefaultOpenIDConnectClientConfiguration.UserinfoSignedResponseAlg) switch config.Clients[c].UserinfoSignedResponseKeyID { case "": switch config.Clients[c].UserinfoSignedResponseAlg { case "", oidc.SigningAlgNone, oidc.SigningAlgRSAUsingSHA256: break default: if !utils.IsStringInSlice(config.Clients[c].UserinfoSignedResponseAlg, config.Discovery.ResponseObjectSigningAlgs) { val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCUsrSigAlg, strJoinOr(append(config.Discovery.ResponseObjectSigningAlgs, oidc.SigningAlgNone)), config.Clients[c].UserinfoSignedResponseAlg)) } } default: if !utils.IsStringInSlice(config.Clients[c].UserinfoSignedResponseKeyID, config.Discovery.ResponseObjectSigningKeyIDs) { val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCUsrSigKID, strJoinOr(config.Discovery.ResponseObjectSigningKeyIDs), config.Clients[c].UserinfoSignedResponseKeyID)) } else { config.Clients[c].UserinfoSignedResponseAlg = getResponseObjectAlgFromKID(config, config.Clients[c].UserinfoSignedResponseKeyID, config.Clients[c].UserinfoSignedResponseAlg) } } } func validateOIDDClientSigningAlgsIntrospection(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { config.Clients[c].IntrospectionSignedResponseAlg, config.Clients[c].IntrospectionSignedResponseKeyID = validateOIDCClientAlgKIDDefault(config, config.Clients[c].IntrospectionSignedResponseAlg, config.Clients[c].IntrospectionSignedResponseKeyID, schema.DefaultOpenIDConnectClientConfiguration.IntrospectionSignedResponseAlg) switch config.Clients[c].IntrospectionSignedResponseKeyID { case "": switch config.Clients[c].IntrospectionSignedResponseAlg { case "", oidc.SigningAlgNone, oidc.SigningAlgRSAUsingSHA256: break default: if !utils.IsStringInSlice(config.Clients[c].IntrospectionSignedResponseAlg, config.Discovery.ResponseObjectSigningAlgs) { val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCIntrospectionSigAlg, strJoinOr(append(config.Discovery.ResponseObjectSigningAlgs, oidc.SigningAlgNone)), config.Clients[c].IntrospectionSignedResponseAlg)) } } default: if !utils.IsStringInSlice(config.Clients[c].IntrospectionSignedResponseKeyID, config.Discovery.ResponseObjectSigningKeyIDs) { val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCIntrospectionSigKID, strJoinOr(config.Discovery.ResponseObjectSigningKeyIDs), config.Clients[c].IntrospectionSignedResponseKeyID)) } else { config.Clients[c].IntrospectionSignedResponseAlg = getResponseObjectAlgFromKID(config, config.Clients[c].IntrospectionSignedResponseKeyID, config.Clients[c].IntrospectionSignedResponseAlg) } } } func validateOIDDClientSigningAlgsJARM(c int, config *schema.IdentityProvidersOpenIDConnect, val *schema.StructValidator) { config.Clients[c].AuthorizationSignedResponseAlg, config.Clients[c].AuthorizationSignedResponseKeyID = validateOIDCClientAlgKIDDefault(config, config.Clients[c].AuthorizationSignedResponseAlg, config.Clients[c].AuthorizationSignedResponseKeyID, schema.DefaultOpenIDConnectClientConfiguration.AuthorizationSignedResponseAlg) switch config.Clients[c].AuthorizationSignedResponseKeyID { case "": switch config.Clients[c].AuthorizationSignedResponseAlg { case "", oidc.SigningAlgNone, oidc.SigningAlgRSAUsingSHA256: break default: if !utils.IsStringInSlice(config.Clients[c].AuthorizationSignedResponseAlg, config.Discovery.ResponseObjectSigningAlgs) { val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCAuthorizationSigAlg, strJoinOr(config.Discovery.ResponseObjectSigningAlgs), config.Clients[c].AuthorizationSignedResponseAlg)) } } default: if !utils.IsStringInSlice(config.Clients[c].AuthorizationSignedResponseKeyID, config.Discovery.ResponseObjectSigningKeyIDs) { val.Push(fmt.Errorf(errFmtOIDCClientInvalidValue, config.Clients[c].ID, attrOIDCAuthorizationSigKID, strJoinOr(config.Discovery.ResponseObjectSigningKeyIDs), config.Clients[c].AuthorizationSignedResponseKeyID)) } else { config.Clients[c].AuthorizationSignedResponseAlg = getResponseObjectAlgFromKID(config, config.Clients[c].AuthorizationSignedResponseKeyID, config.Clients[c].AuthorizationSignedResponseAlg) } } } func validateOIDCClientAlgKIDDefault(config *schema.IdentityProvidersOpenIDConnect, algCurrent, kidCurrent, algDefault string) (alg, kid string) { alg, kid = algCurrent, kidCurrent switch balg, bkid := len(alg) != 0, len(kid) != 0; { case balg && bkid: return case !balg && !bkid: if algDefault == "" { return } alg = algDefault } switch balg, bkid := len(alg) != 0, len(kid) != 0; { case !balg && !bkid: return case !bkid: for _, jwk := range config.IssuerPrivateKeys { if alg == jwk.Algorithm { kid = jwk.KeyID return } } case !balg: for _, jwk := range config.IssuerPrivateKeys { if kid == jwk.KeyID { alg = jwk.Algorithm return } } } return }
package cidenc import ( "testing" cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid" mbase "gx/ipfs/QmekxXDhCxCJRNuzmHreuaT3BsuJcsjcXWNrtV9C8DRHtd/go-multibase" ) func TestCidEncoder(t *testing.T) { cidv0str := "QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n" cidv1str := "zdj7Wkkhxcu2rsiN6GUyHCLsSLL47kdUNfjbFqBUUhMFTZKBi" cidb32str := "bafybeihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku" cidv0, _ := cid.Decode(cidv0str) cidv1, _ := cid.Decode(cidv1str) testEncode := func(enc Encoder, cid cid.Cid, expect string) { actual := enc.Encode(cid) if actual != expect { t.Errorf("%+v.Encode(%s): expected %s but got %s", enc, cid, expect, actual) } } testRecode := func(enc Encoder, cid string, expect string) { actual, err := enc.Recode(cid) if err != nil { t.Errorf("%+v.Recode(%s): %s", enc, cid, err) return } if actual != expect { t.Errorf("%+v.Recode(%s): expected %s but got %s", enc, cid, expect, actual) } } enc := Encoder{Base: mbase.MustNewEncoder(mbase.Base58BTC), Upgrade: false} testEncode(enc, cidv0, cidv0str) testEncode(enc, cidv1, cidv1str) testRecode(enc, cidv0str, cidv0str) testRecode(enc, cidv1str, cidv1str) testRecode(enc, cidb32str, cidv1str) enc = Encoder{Base: mbase.MustNewEncoder(mbase.Base58BTC), Upgrade: true} testEncode(enc, cidv0, cidv1str) testEncode(enc, cidv1, cidv1str) testRecode(enc, cidv0str, cidv1str) testRecode(enc, cidv1str, cidv1str) testRecode(enc, cidb32str, cidv1str) enc = Encoder{Base: mbase.MustNewEncoder(mbase.Base32), Upgrade: false} testEncode(enc, cidv0, cidv0str) testEncode(enc, cidv1, cidb32str) testRecode(enc, cidv0str, cidv0str) testRecode(enc, cidv1str, cidb32str) testRecode(enc, cidb32str, cidb32str) enc = Encoder{Base: mbase.MustNewEncoder(mbase.Base32), Upgrade: true} testEncode(enc, cidv0, cidb32str) testEncode(enc, cidv1, cidb32str) testRecode(enc, cidv0str, cidb32str) testRecode(enc, cidv1str, cidb32str) testRecode(enc, cidb32str, cidb32str) }
package tgo import ( "fmt" "strconv" ) func UtilFloat64ToInt(value float64, multiplied float64) (intValue int, err error) { aString := fmt.Sprintf("%.0f", value*multiplied) intValue, err = strconv.Atoi(aString) if err != nil { UtilLogErrorf("%f to int failed,error:%s", value, err.Error()) } return }
package main import "fmt" var test = 1 func init() { test++ fmt.Println("First init called.", test) } func init() { test++ fmt.Println("Second init called.", test) } func main() { test++ fmt.Println("Main function called.", test) }
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * Unless required by applicable law or agreed to in writing, software distributed under, * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package constants // k8s 资源类型 const ( // Node ... Node = "Node" // NS ... NS = "Namespace" // Deploy ... Deploy = "Deployment" // RS ... RS = "ReplicaSet" // DS ... DS = "DaemonSet" // STS ... STS = "StatefulSet" // CJ ... CJ = "CronJob" // Job ... Job = "Job" // Po ... Po = "Pod" // Ing ... Ing = "Ingress" // SVC ... SVC = "Service" // EP ... EP = "Endpoints" // CM ... CM = "ConfigMap" // Secret ... Secret = "Secret" // PV ... PV = "PersistentVolume" // PVC ... PVC = "PersistentVolumeClaim" // SC ... SC = "StorageClass" // SA ... SA = "ServiceAccount" // HPA ... HPA = "HorizontalPodAutoscaler" // CRD ... CRD = "CustomResourceDefinition" // CObj ... CObj = "CustomObject" ) // BCS 提供自定义类型 const ( // GDeploy ... GDeploy = "GameDeployment" // GSTS ... GSTS = "GameStatefulSet" // HookTmpl ... HookTmpl = "HookTemplate" // HookRun ... HookRun = "HookRun" ) const ( // WatchTimeout 执行资源变动 Watch 超时时间 30 分钟 WatchTimeout = 30 * 60 ) const ( // NamespacedScope 命名空间维度 NamespacedScope = "Namespaced" // ClusterScope 集群维度 ClusterScope = "Cluster" ) const ( // MasterNodeLabelKey Node 存在该标签,且值为 "true" 说明是 master MasterNodeLabelKey = "node-role.kubernetes.io/master" ) const ( // EditModeAnnoKey 资源被编辑的模式,表单为 form,Key 不存在或 Manifest 则为 Yaml 模式 EditModeAnnoKey = "io.tencent.bcs.editFormat" ) const ( // CreatorAnnoKey 创建者 CreatorAnnoKey = "io.tencent.paas.creator" // UpdaterAnnoKey 更新者,为保持与 bcs-ui 中的一致,还是使用 updator(typo) UpdaterAnnoKey = "io.tencent.paas.updator" ) const ( // EditModeForm 资源编辑模式 - 表单 EditModeForm = "form" // EditModeYaml 资源编辑模式 - Yaml EditModeYaml = "yaml" ) const ( // MetricResCPU 指标资源:CPU MetricResCPU = "cpu" // MetricResMem 指标资源:内存 MetricResMem = "memory" ) const ( // CustomApiVersion 自定义apiVersion CustomApiVersion = "networkextension.bkbcs.tencent.com/v1" ) // RemoveResVersionKinds 更新时强制移除 resourceVersion 的资源类型 // 添加 HPA 原因是,HPA 每次做扩缩容操作,集群均会更新资源(rv),过于频繁导致用户编辑态的 rv 过期 & 冲突导致无法更新 // 理论上所有资源都可能会有这样的问题,不止其他用户操作,集群也可能操作导致 rv 过期,但是因 HPA 过于频繁,因此这里配置需要移除 rv // 注意:该行为相当于强制更新,会覆盖集群中的该资源,另外需要注意的是 service 这类资源必须指定 resourceVersion,否则报错如下: // Service "service-xxx" is invalid: metadata.resourceVersion: Invalid value: "": must be specified for an update var RemoveResVersionKinds = []string{HPA} const ( // CurrentRevision 当前deployment 版本 CurrentRevision = "current_revision" // RolloutRevision 要回滚的deployment 版本 RolloutRevision = "rollout_revision" // Revision deployment 版本 Revision = "deployment.kubernetes.io/revision" // ChangeCause deployment更新原因 ChangeCause = "deployment.kubernetes.io/change-cause" )
package acoustid import ( "bytes" "encoding/json" "io/ioutil" "net/http" "net/url" "strconv" "strings" "time" hc "github.com/ocramh/fingerprinter/internal/httpclient" fp "github.com/ocramh/fingerprinter/pkg/fingerprint" ) const ( // AcoustIDBaseURL is the base URL used for queries the acoustid API AcoustIDBaseURL = "https://api.acoustid.org/v2/lookup" // The delay requests should respect when being fired in succession AcoustIDReqDelay = 1 * time.Second ) var ( // lookupMeta is the metadata that will be added to a lookup response. // Recordings and releasegroups ids values can be used to query the MusicBrainz API lookupMeta = []string{"recordings", "recordingids", "releases", "releasesids", "releasegroups"} ) // AcoustID is the type responsible for interacting with the AcoustID API. // It requires an API key that can be generated by registering an application at // https://acoustid.org/login?return_url=https%3A%2F%2Facoustid.org%2Fnew-application type AcoustID struct { apiKey string } // NewAcoustID is the AcoustID constructor func NewAcoustID(k string) *AcoustID { return &AcoustID{k} } // LookupFingerprint uses audio fingerprints and duration values to search the // AcoustID fingerprint database and return the corresponding track ID and MusicBrainz // recording ID if a match was found func (a *AcoustID) LookupFingerprint(f *fp.Fingerprint, withRetry bool) (*AcoustIDLookupResp, error) { resp, err := a.doHTTPRequest((f)) if err != nil { return nil, err } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { if resp.StatusCode == http.StatusServiceUnavailable { if withRetry { time.Sleep(retryAfterSec(resp)) return a.LookupFingerprint(f, false) } return nil, hc.NewHTTPError(http.StatusServiceUnavailable, "upstream service not available") } return nil, handleAcoustIDErrResp(resp) } var lookupResp AcoustIDLookupResp breader := bytes.NewReader(b) err = json.NewDecoder(breader).Decode(&lookupResp) if err != nil { return nil, err } return &lookupResp, nil } func retryAfterSec(r *http.Response) time.Duration { retryAfterH := r.Header.Get("Retry-After") retryAfterSec, err := strconv.Atoi(retryAfterH) if err != nil { return AcoustIDReqDelay } return time.Duration(retryAfterSec) * time.Second } func (a *AcoustID) buildLookupQueryVals(f *fp.Fingerprint) url.Values { values := url.Values{} values.Set("client", a.apiKey) values.Add("meta", strings.Join(lookupMeta, " ")) values.Add("duration", strconv.Itoa(int(f.Duration))) values.Add("fingerprint", f.Value) return values } func (a *AcoustID) doHTTPRequest(f *fp.Fingerprint) (*http.Response, error) { encodedPayload := a.buildLookupQueryVals(f).Encode() req, err := http.NewRequest("POST", AcoustIDBaseURL, strings.NewReader(encodedPayload)) if err != nil { return nil, err } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") httpClient := hc.NewClient() return httpClient.Do(req) } func handleAcoustIDErrResp(resp *http.Response) error { var errResp AcoustErrResp err := json.NewDecoder(resp.Body).Decode(&errResp) if err != nil { return err } return hc.NewHTTPError(resp.StatusCode, errResp.Error.Message) } // ACResultsByScore is the ACLookupResult implementation of the sort.Interface // used for sorting results by score type ACResultsByScore []ACLookupResult func (a ACResultsByScore) Len() int { return len(a) } func (a ACResultsByScore) Swap(i int, j int) { a[i], a[j] = a[j], a[i] } func (a ACResultsByScore) Less(i, j int) bool { return a[i].Score > a[j].Score }
package main import "fmt" // 方法 type dog struct { name string } // 构造函数 func newDog(name string) dog { return dog{ name, } } //方法作用域特定类型的函数 //接受dog类型变量来调用,这里接受者是dog类型变量 //接受者表示的是调用该方法的具体类型变量,多用类型首字母表示(类似java this,python self) func (d dog) wang() { fmt.Printf("%s:汪汪汪\n", d.name) } func main() { d1 := newDog("哈士奇") d1.wang() }
package handlers import ( "net/http" "github.com/Khigashiguchi/khigashiguchi.com/api/domain/entity" "github.com/Khigashiguchi/khigashiguchi.com/api/infrastructure/repository" "github.com/Khigashiguchi/khigashiguchi.com/api/interfaces/presenter" "github.com/Khigashiguchi/khigashiguchi.com/api/usecase" "github.com/gin-gonic/gin/json" ) // Handler is interface of handling request. type Handler interface { Handler(w http.ResponseWriter, r *http.Request) } type getEntriesHandler struct { UseCase usecase.GetEntriesUseCase } // GetEntriesHandler handle request GET /entries. func (h *getEntriesHandler) Handler(w http.ResponseWriter, r *http.Request) { entries, err := h.UseCase.Run() if err != nil { presenter.RespondErrorJson(w, "Internal Server Error", http.StatusInternalServerError) return } res := presenter.GetEntriesResponse{ Entities: entries, } presenter.RespondJson(w, res, http.StatusOK) } // NewGetEntriesHandler create new handler of getting entries. func NewGetEntriesHandler(db repository.DB) Handler { return &getEntriesHandler{UseCase: usecase.NewGetEntriesUseCase(db)} } type postEntriesHandler struct { UseCase usecase.PostEntriesUseCase } func (h *postEntriesHandler) Handler(w http.ResponseWriter, r *http.Request) { entry := entity.Entry{} if err := json.NewDecoder(r.Body).Decode(&entry); err != nil { presenter.RespondErrorJson(w, "invalid parameter", http.StatusBadRequest) return } if err := h.UseCase.Run(entry); err != nil { presenter.RespondJson(w, err.Error(), http.StatusBadRequest) return } } func NewPostEntriesHandler(db repository.Beginner) Handler { return &postEntriesHandler{UseCase: usecase.NewPostEntriesUseCase(db)} }
package knapsackproblem01 import "testing" func TestKnapsackProblem01(t *testing.T) { type Knapsack struct { w []int v []int c int } testData := []Knapsack{ Knapsack{ w: []int{1, 2, 3}, v: []int{6, 10, 12}, c: 5, }, Knapsack{ w: []int{}, v: []int{}, c: 5, }, } expectedData := []int{22, 0} for index, data := range testData { if res := knapsack01(data.w, data.v, data.c); res != expectedData[index] { t.Errorf("expected %d, got %d", expectedData[index], res) } } knapsack := Knapsack{ w: []int{1, 2, 3, 3}, v: []int{6, 10, 12}, c: 5, } defer func() { if err := recover(); err == nil { t.Error("Failed, panic error can't catch") } }() knapsack01(knapsack.w, knapsack.v, knapsack.c) }
package main import "fmt" func main() { var age int //variable declaration fmt.Println("My age is ", age) //uninitialised variables are assigned with default value zero age = 10 fmt.Println("My age is ", age) age++ fmt.Println("My age is ", age) var superAge int = 20 //varibale with initial value fmt.Println("My age is ", superAge) }
package main import ( "fmt" "github.com/bearname/videohost/internal/common/infrarstructure/mysql" _ "github.com/go-sql-driver/mysql" log "github.com/sirupsen/logrus" "io/ioutil" "os" "path/filepath" ) func main() { var connector mysql.ConnectorImpl err := connector.Connect("root", "123", "localhost:3306", "video") if err != nil { fmt.Println("unable to connect to connector" + err.Error()) } defer connector.Close() rows, err := connector.GetDb().Query("SELECT id_video FROM video WHERE quality = ''") if err != nil { fmt.Println("unable to connect to connector" + err.Error()) } videoDirs := make([]string, 0) for rows.Next() { var videoId string err = rows.Scan(&videoId) if err == nil { videoDirs = append(videoDirs, videoId) } } root := "C:\\Users\\mikha\\go\\src\\videohost\\bin\\videoserver\\content\\" files, err := ioutil.ReadDir(root) if err != nil { log.Fatal(err) } fmt.Println(videoDirs) fmt.Println(len(files)) for _, f := range files { if !contains(videoDirs, f.Name()) { err = RemoveContents(root + f.Name()) if err != nil { fmt.Println(f.Name()) fmt.Println(err.Error()) } dir := root + f.Name() fmt.Println(dir) err = os.Remove(dir) if err != nil { log.Fatal(err) } } } } func contains(s []string, e string) bool { for _, a := range s { if a == e { return true } } return false } func RemoveContents(dir string) error { d, err := os.Open(dir) if err != nil { return err } defer d.Close() names, err := d.Readdirnames(-1) if err != nil { return err } for _, name := range names { err = os.RemoveAll(filepath.Join(dir, name)) if err != nil { return err } } return nil }
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func increasingBST(root *TreeNode) *TreeNode { if root==nil{return nil} res :=[]int{} res = iot(root, res) head:=&TreeNode{Val: res[0]} tmp := head for i:=1;i<len(res);i++{ tmp.Right = &TreeNode{Val: res[i]} tmp = tmp.Right } return head } func iot(node *TreeNode,res []int) []int{ if node.Left!=nil{res=iot(node.Left,res)} res = append(res,node.Val) if node.Right!=nil{res=iot(node.Right,res)} return res }
/* * @lc app=leetcode.cn id=1 lang=golang * * [1] 两数之和 * * https://leetcode-cn.com/problems/two-sum/description/ * * algorithms * Easy (46.44%) * Likes: 5960 * Dislikes: 0 * Total Accepted: 500.1K * Total Submissions: 1.1M * Testcase Example: '[2,7,11,15]\n9' * * 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 * * 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 * * 示例: * * 给定 nums = [2, 7, 11, 15], target = 9 * * 因为 nums[0] + nums[1] = 2 + 7 = 9 * 所以返回 [0, 1] * * */ func twoSum(nums []int, target int) []int { var a []int b := 0 for key, i := range nums { for key2, j := range nums { if (target == (i + j)) && (key != key2) { a = append(a, key) a = append(a, key2) b = 1 break } } if b == 1 { break } } return a }
package main import ( _ "github.com/openshift-metal3/terraform-provider-ironic" )
// https://tour.golang.org/concurrency/10 // This code shows a good example on how to wait // until all chidren routines done package main import ( "fmt" "sync" ) type Fetcher interface { // Fetch returns the body of URL and // a slice of URLs found on that page. Fetch(url string) (body string, urls []string, err error) } type URLs struct { List map[string]bool mux sync.Mutex } func (urls URLs) Exists(url string) bool { urls.mux.Lock() defer urls.mux.Unlock() return urls.List[url] } func (urls URLs) Set(url string) { urls.mux.Lock() urls.List[url] = true urls.mux.Unlock() } // Crawl uses fetcher to recursively crawl // pages starting with url, to a maximum of depth. func Crawl(url string, depth int, fetcher Fetcher, fetched *URLs, res chan string) { defer close(res) if depth <= 0 { return } if fetched.Exists(url) { return } fetched.Set(url) body, urls, err := fetcher.Fetch(url) if err != nil { fmt.Println(err) return } res <- fmt.Sprintf("found: %s %q\n", url, body) // A parent routine will wait all children routine until they finished. // Otherwise the main func will just exit childrenRes := make([]chan string, len(urls)) for i, _ := range childrenRes { childrenRes[i] = make(chan string) } for i, u := range urls { go Crawl(u, depth-1, fetcher, fetched, childrenRes[i]) } for i := range childrenRes { for r := range childrenRes[i] { res <- r } } return } func main() { fetched := &URLs{List: make(map[string]bool)} res := make(chan string) go Crawl("http://golang.org/", 4, fetcher, fetched, res) for r := range res { fmt.Printf(r) } } // fakeFetcher is Fetcher that returns canned results. type fakeFetcher map[string]*fakeResult type fakeResult struct { body string urls []string } func (f fakeFetcher) Fetch(url string) (string, []string, error) { if res, ok := f[url]; ok { return res.body, res.urls, nil } return "", nil, fmt.Errorf("not found: %s", url) } // fetcher is a populated fakeFetcher. var fetcher = fakeFetcher{ "http://golang.org/": &fakeResult{ "The Go Programming Language", []string{ "http://golang.org/pkg/", "http://golang.org/cmd/", }, }, "http://golang.org/pkg/": &fakeResult{ "Packages", []string{ "http://golang.org/", "http://golang.org/cmd/", "http://golang.org/pkg/fmt/", "http://golang.org/pkg/os/", }, }, "http://golang.org/pkg/fmt/": &fakeResult{ "Package fmt", []string{ "http://golang.org/", "http://golang.org/pkg/", }, }, "http://golang.org/pkg/os/": &fakeResult{ "Package os", []string{ "http://golang.org/", "http://golang.org/pkg/", }, }, }
package models import ( "encoding/json" "io/ioutil" "testing" ) func BenchmarkCreateMe(b *testing.B) { data, _ := ioutil.ReadFile("./tests/me.json") meExampleJson := string(data) for i := 0; i < b.N; i++ { sub := Me{} json.Unmarshal([]byte(meExampleJson), &sub) } }
package main import ( "bufio" "fmt" "os/exec" "strconv" "sync" "time" "strings" "github.com/vkorn/go-miio" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/util" "net/http" "net/url" ) const ( mac_start = 14 mac_end = 26 v_type_start = 66 v_type_end = 70 v_start = 70 v_end =74 ) func hcidump(data chan []byte, quit chan bool) { wg := new(sync.WaitGroup) cmd := exec.Command("hcidump", "-R") c := make(chan struct{}) wg.Add(1) go func(cmd *exec.Cmd, c chan struct{}) { defer wg.Done() stdout, err := cmd.StdoutPipe() if err != nil { panic(err) } <-c scanner := bufio.NewScanner(stdout) for scanner.Scan() { select { case <-quit: fmt.Println("recv: quit") return case data<-scanner.Bytes(): } } }(cmd, c) c<-struct{}{} fmt.Println("hcidump start") cmd.Start() fmt.Println("hcidump started") wg.Wait() fmt.Println("hcidump exited") } func parseRawPkt(raw string) (m,t string, v int64) { if len(raw) > v_end { mac := raw[mac_start:mac_end] tmp_t := raw[v_type_start:v_type_end] s, err := strconv.ParseInt(raw[v_start+2:v_end]+raw[v_start:v_start+2], 16, 32) if err != nil { fmt.Println(raw, err) return } m,t,v = mac,tmp_t,s } return } var ( total int64 count int64 ) func autoTmp(m,t string, v int64) { if m == mac_filter && t == type_filter { count = count + 1 total = total + v if count == counter_for_avg { avg := float64(total) / float64(count) total = 0 count = 0 mux.Lock() //制冷模式下,高出指定温度开始启动电源制冷;制热模式下,低于指定温度开始启动电源制热; if (tmp_ctrl_mode == "cool" && avg > tmp_ctrl_limit) || (tmp_ctrl_mode == "heat" && avg < tmp_ctrl_limit) { if onTime == zeroTime { log(time.Now().Format("20060102 15:04:05"), " ", tmp_ctrl_mode+"_on", " ", plg.On(), " ", avg) onTime = time.Now() } } else { log(time.Now().Format("20060102 15:04:05"), " ", tmp_ctrl_mode+"_off", " ", plg.Off(), " ", avg) onTime = zeroTime } mux.Unlock() } } } func ctrl() { data := make(chan []byte, 1024) quit := make(chan bool, 1) go hcidump(data, quit) t := time.NewTicker(time.Minute * 15) lines:="" r:=strings.NewReplacer(" ","","\n","") for { select { case d := <-data: if d[0]=='>' { raw:=r.Replace(lines) m, t, v := parseRawPkt(raw) autoTmp(m, t, v) lines=string(d[1:]) } else { lines=lines+string(d) } case <-t.C: quit <- true go hcidump(data, quit) } } } var ( zeroTime time.Time = time.Unix(0, 0) onTime time.Time = zeroTime mux *sync.Mutex = new(sync.Mutex) ) func autoOff() { t:=time.NewTicker(time.Second*time.Duration(getWithDefaultInt("auto_off_freq", 10))) for { select { case c:=<-t.C: loadConf() mux.Lock() if onTime!=zeroTime { last := c.Sub(onTime) if last.Seconds() > float64(tmp_ctrl_time) { log(time.Now().Format("20060102 15:04:05")," ", tmp_ctrl_mode+"_off"," ", plg.Off()," ", "timer_off:"," ", tmp_ctrl_time) onTime= zeroTime } } mux.Unlock() } } } func log(val ...interface{}) { out:=fmt.Sprint(val...) fmt.Println(out) gdb.Put([]byte("log_"+time.Now().Format("20060102150405")), []byte(out), nil) } func getWithDefaultInt(key string, val int) int { vb,err:=gdb.Get([]byte("conf_"+key), nil) if err!=nil { vb=[]byte(strconv.Itoa(val)) gdb.Put([]byte("conf_"+key), vb, nil) } v,e:=strconv.Atoi(string(vb)) if e!=nil { return val } return v } func setKeyVal(key, val string) string { err:=gdb.Put([]byte("conf_"+key), []byte(val),nil) if err!=nil { return err.Error() } return val } func getWithDefault(key, dft string) string { vb,err:=gdb.Get([]byte("conf_"+key), nil) if err!=nil { vb=[]byte(dft) gdb.Put([]byte("conf_"+key), vb, nil) } return string(vb) } func iterLog(prefix string) []string { ret := make([]string, 0) iter := gdb.NewIterator(util.BytesPrefix([]byte("log_"+prefix)), nil) for iter.Next() { ret = append(ret, string(iter.Value())) } iter.Release() return ret } func iterConf() []string { ret := make([]string, 0) iter := gdb.NewIterator(util.BytesPrefix([]byte("conf_")), nil) for iter.Next() { ret = append(ret, string(iter.Key())[5:]+":"+string(iter.Value())) } iter.Release() return ret } var ( tmp_ctrl_limit float64 tmp_ctrl_time int64 tmp_ctrl_mode string counter_for_avg int64 plug_ip string plug_token string mac_filter string type_filter string ) func loadConf() { tmp_ctrl_limit = float64(getWithDefaultInt("tmp_will_reverse",2501))/10 counter_for_avg = int64(getWithDefaultInt("counter_for_avg",10)) tmp_ctrl_time = int64(getWithDefaultInt("tmp_ctrl_time",10)) tmp_ctrl_mode = getWithDefault("tmp_ctrl_mode", "cool") //heat plug_ip = getWithDefault("plug_ip", "192.168.50.143") plug_token = getWithDefault("plug_token","????") mac_filter = getWithDefault("mac_filter", "5DA8DEA8654C") type_filter = getWithDefault("type_filter", "1004") } func httpServer() { helloHandler := func(w http.ResponseWriter, r *http.Request) { queryForm, err := url.ParseQuery(r.URL.RawQuery) fmt.Println(r.URL.RawQuery) if err == nil && len(queryForm["cmd"]) > 0 { cmd:=queryForm["cmd"][0] if cmd=="conf" { for _,v:=range iterConf() { fmt.Fprintf(w, "%s\n", v) } } else if cmd=="set" { keys:=queryForm["key"] vals:=queryForm["val"] if len(keys)>0 && len(vals)>0 { fmt.Fprintln(w, setKeyVal(keys[0], vals[0])) } } else { pres:=queryForm["pre"] pre:=time.Now().Format("2006010215") if len(pres)>0 { pre = pres[0] } for _, v := range iterLog(pre) { fmt.Fprintf(w, "%s\n", v) } } } } http.HandleFunc("/autotmp", helloHandler) fmt.Println(http.ListenAndServe(":8080", nil)) } var plg *miio.Plug var gdb *leveldb.DB func main() { db, err := leveldb.OpenFile("/root/dbs", nil) if err !=nil { fmt.Println(err) return } defer db.Close() gdb = db loadConf() plug, err := miio.NewPlug(plug_ip, plug_token) if err != nil { fmt.Println(err) return } plg=plug go autoOff() go ctrl() httpServer() }
package vsphere import ( "net/netip" "testing" "github.com/google/go-cmp/cmp" "github.com/pkg/errors" "github.com/stretchr/testify/assert" "sigs.k8s.io/yaml" machineapi "github.com/openshift/api/machine/v1beta1" "github.com/openshift/installer/pkg/types" "github.com/openshift/installer/pkg/types/conversion" "github.com/openshift/installer/pkg/types/vsphere" ) const testClusterID = "test" var installConfigSample = ` apiVersion: v1 baseDomain: example.com controlPlane: name: master platform: vsphere: zones: - deployzone-us-east-1a - deployzone-us-east-2a - deployzone-us-east-3a cpus: 8 coresPerSocket: 2 memoryMB: 24576 osDisk: diskSizeGB: 512 replicas: 3 compute: - name: worker platform: vsphere: zones: - deployzone-us-east-1a - deployzone-us-east-2a - deployzone-us-east-3a cpus: 8 coresPerSocket: 2 memoryMB: 24576 osDisk: diskSizeGB: 512 replicas: 3 metadata: name: test-cluster platform: vSphere: vcenters: - server: your.vcenter.example.com username: username password: password datacenters: - dc1 - dc2 - dc3 - dc4 failureDomains: - name: deployzone-us-east-1a server: your.vcenter.example.com region: us-east zone: us-east-1a topology: resourcePool: /dc1/host/c1/Resources/rp1 folder: /dc1/vm/folder1 datacenter: dc1 computeCluster: /dc1/host/c1 networks: - network1 datastore: /dc1/datastore/datastore1 - name: deployzone-us-east-2a server: your.vcenter.example.com region: us-east zone: us-east-2a topology: resourcePool: /dc2/host/c2/Resources/rp2 folder: /dc2/vm/folder2 datacenter: dc2 computeCluster: /dc2/host/c2 networks: - network1 datastore: /dc2/datastore/datastore2 - name: deployzone-us-east-3a server: your.vcenter.example.com region: us-east zone: us-east-3a topology: resourcePool: /dc3/host/c3/Resources/rp3 folder: /dc3/vm/folder3 datacenter: dc3 computeCluster: /dc3/host/c3 networks: - network1 datastore: /dc3/datastore/datastore3 - name: deployzone-us-east-4a server: your.vcenter.example.com region: us-east zone: us-east-4a topology: resourcePool: /dc4/host/c4/Resources/rp4 folder: /dc4/vm/folder4 datacenter: dc4 computeCluster: /dc4/host/c4 networks: - network1 datastore: /dc4/datastore/datastore4 hosts: - role: bootstrap networkDevice: ipaddrs: - 192.168.101.240/24 gateway: 192.168.101.1 nameservers: - 192.168.101.2 - role: control-plane failureDomain: deployzone-us-east-1a networkDevice: ipAddrs: - 192.168.101.241/24 gateway: 192.168.101.1 nameservers: - 192.168.101.2 - role: control-plane failureDomain: deployzone-us-east-2a networkDevice: ipAddrs: - 192.168.101.242/24 gateway: 192.168.101.1 nameservers: - 192.168.101.2 - role: control-plane failureDomain: deployzone-us-east-3a networkDevice: ipAddrs: - 192.168.101.243/24 gateway: 192.168.101.1 nameservers: - 192.168.101.2 - role: compute failureDomain: deployzone-us-east-1a networkDevice: ipAddrs: - 192.168.101.244/24 gateway: 192.168.101.1 nameservers: - 192.168.101.2 - role: compute failureDomain: deployzone-us-east-2a networkDevice: ipAddrs: - 192.168.101.245/24 gateway: 192.168.101.1 nameservers: - 192.168.101.2 - role: compute failureDomain: deployzone-us-east-3a networkDevice: ipAddrs: - 192.168.101.246/24 gateway: 192.168.101.1 nameservers: - 192.168.101.2 pullSecret: sshKey:` var machinePoolReplicas = int64(3) var machinePoolMinReplicas = int64(2) var machinePoolValidZones = types.MachinePool{ Name: "master", Replicas: &machinePoolReplicas, Platform: types.MachinePoolPlatform{ VSphere: &vsphere.MachinePool{ NumCPUs: 4, NumCoresPerSocket: 2, MemoryMiB: 16384, OSDisk: vsphere.OSDisk{ DiskSizeGB: 60, }, Zones: []string{ "deployzone-us-east-1a", "deployzone-us-east-2a", "deployzone-us-east-3a", }, }, }, Hyperthreading: "true", Architecture: types.ArchitectureAMD64, } var machinePoolReducedZones = types.MachinePool{ Name: "master", Replicas: &machinePoolReplicas, Platform: types.MachinePoolPlatform{ VSphere: &vsphere.MachinePool{ NumCPUs: 4, NumCoresPerSocket: 2, MemoryMiB: 16384, OSDisk: vsphere.OSDisk{ DiskSizeGB: 60, }, Zones: []string{ "deployzone-us-east-1a", "deployzone-us-east-2a", }, }, }, Hyperthreading: "true", Architecture: types.ArchitectureAMD64, } var machinePoolUndefinedZones = types.MachinePool{ Name: "master", Replicas: &machinePoolReplicas, Platform: types.MachinePoolPlatform{ VSphere: &vsphere.MachinePool{ NumCPUs: 4, NumCoresPerSocket: 2, MemoryMiB: 16384, OSDisk: vsphere.OSDisk{ DiskSizeGB: 60, }, Zones: []string{ "region-dc1-zone-undefined", }, }, }, Hyperthreading: "true", Architecture: types.ArchitectureAMD64, } func parseInstallConfig() (*types.InstallConfig, error) { config := &types.InstallConfig{} if err := yaml.Unmarshal([]byte(installConfigSample), config); err != nil { return nil, errors.Wrapf(err, "failed to unmarshal sample install config") } // Upconvert any deprecated fields if err := conversion.ConvertInstallConfig(config); err != nil { return nil, errors.Wrap(err, "failed to upconvert install config") } return config, nil } func assertOnUnexpectedErrorState(t *testing.T, expectedError string, err error) { t.Helper() if expectedError == "" && err != nil { t.Errorf("unexpected error encountered: %s", err.Error()) } else if expectedError != "" { if err != nil { if expectedError != err.Error() { t.Errorf("expected error does not match intended error. should be: %s was: %s", expectedError, err.Error()) } } else { t.Errorf("expected error but error did not occur") } } } func TestConfigMasters(t *testing.T) { clusterID := testClusterID installConfig, err := parseInstallConfig() if err != nil { assert.Errorf(t, err, "unable to parse sample install config") return } defaultClusterResourcePool, err := parseInstallConfig() if err != nil { t.Error(err) return } defaultClusterResourcePool.VSphere.FailureDomains[0].Topology.ResourcePool = "" testCases := []struct { testCase string expectedError string machinePool *types.MachinePool workspaces []machineapi.Workspace installConfig *types.InstallConfig maxAllowedWorkspaceMatches int minAllowedWorkspaceMatches int }{ { testCase: "zones distributed among control plane machines(zone count matches machine count)", machinePool: &machinePoolValidZones, maxAllowedWorkspaceMatches: 1, installConfig: installConfig, workspaces: []machineapi.Workspace{ { Server: "your.vcenter.example.com", Datacenter: "dc1", Folder: "/dc1/vm/folder1", Datastore: "/dc1/datastore/datastore1", ResourcePool: "/dc1/host/c1/Resources/rp1", }, { Server: "your.vcenter.example.com", Datacenter: "dc2", Folder: "/dc2/vm/folder2", Datastore: "/dc2/datastore/datastore2", ResourcePool: "/dc2/host/c2/Resources/rp2", }, { Server: "your.vcenter.example.com", Datacenter: "dc3", Folder: "/dc3/vm/folder3", Datastore: "/dc3/datastore/datastore3", ResourcePool: "/dc3/host/c3/Resources/rp3", }, }, }, { testCase: "undefined zone in machinepool results in error", machinePool: &machinePoolUndefinedZones, installConfig: installConfig, expectedError: "zone [region-dc1-zone-undefined] specified by machinepool is not defined", }, { testCase: "zones distributed among control plane machines(zone count is less than machine count)", machinePool: &machinePoolReducedZones, maxAllowedWorkspaceMatches: 2, minAllowedWorkspaceMatches: 1, installConfig: installConfig, workspaces: []machineapi.Workspace{ { Server: "your.vcenter.example.com", Datacenter: "dc1", Folder: "/dc1/vm/folder1", Datastore: "/dc1/datastore/datastore1", ResourcePool: "/dc1/host/c1/Resources/rp1", }, { Server: "your.vcenter.example.com", Datacenter: "dc2", Folder: "/dc2/vm/folder2", Datastore: "/dc2/datastore/datastore2", ResourcePool: "/dc2/host/c2/Resources/rp2", }, }, }, { testCase: "full path to cluster resource pool when no pool provided via placement constraint", machinePool: &machinePoolValidZones, maxAllowedWorkspaceMatches: 1, minAllowedWorkspaceMatches: 1, installConfig: defaultClusterResourcePool, workspaces: []machineapi.Workspace{ { Server: "your.vcenter.example.com", Datacenter: "dc1", Folder: "/dc1/vm/folder1", Datastore: "/dc1/datastore/datastore1", ResourcePool: "/dc1/host/c1/Resources", }, { Server: "your.vcenter.example.com", Datacenter: "dc2", Folder: "/dc2/vm/folder2", Datastore: "/dc2/datastore/datastore2", ResourcePool: "/dc2/host/c2/Resources/rp2", }, { Server: "your.vcenter.example.com", Datacenter: "dc3", Folder: "/dc3/vm/folder3", Datastore: "/dc3/datastore/datastore3", ResourcePool: "/dc3/host/c3/Resources/rp3", }, }, }, } for _, tc := range testCases { t.Run(tc.testCase, func(t *testing.T) { machines, err := Machines(clusterID, tc.installConfig, tc.machinePool, "", "", "") assertOnUnexpectedErrorState(t, tc.expectedError, err) if len(tc.workspaces) > 0 { var matchCountByIndex []int for range tc.workspaces { matchCountByIndex = append(matchCountByIndex, 0) } for _, machine := range machines { // check if expected workspaces are returned machineWorkspace := machine.Spec.ProviderSpec.Value.Object.(*machineapi.VSphereMachineProviderSpec).Workspace for idx, workspace := range tc.workspaces { if cmp.Equal(workspace, *machineWorkspace) { matchCountByIndex[idx]++ } } } for _, count := range matchCountByIndex { if count > tc.maxAllowedWorkspaceMatches { t.Errorf("machine workspace was enountered too many times[max: %d]", tc.maxAllowedWorkspaceMatches) } if count < tc.minAllowedWorkspaceMatches { t.Errorf("machine workspace was enountered too few times[min: %d]", tc.minAllowedWorkspaceMatches) } } } }) } } func TestHostsToMachines(t *testing.T) { clusterID := testClusterID installConfig, err := parseInstallConfig() if err != nil { assert.Errorf(t, err, "unable to parse sample install config") return } defaultClusterResourcePool, err := parseInstallConfig() if err != nil { t.Error(err) return } defaultClusterResourcePool.VSphere.FailureDomains[0].Topology.ResourcePool = "" testCases := []struct { testCase string expectedError string machinePool *types.MachinePool installConfig *types.InstallConfig role string machineCount int }{ { testCase: "Static IP - ControlPlane", machinePool: &machinePoolValidZones, installConfig: installConfig, role: "master", machineCount: 3, }, { testCase: "Static IP - Compute", machinePool: &machinePoolValidZones, installConfig: installConfig, role: "worker", machineCount: 3, }, } for _, tc := range testCases { t.Run(tc.testCase, func(t *testing.T) { machines, err := Machines(clusterID, tc.installConfig, tc.machinePool, "", tc.role, "") assertOnUnexpectedErrorState(t, tc.expectedError, err) // Check machine counts if len(machines) != tc.machineCount { t.Errorf("machine count (%v) did not match expected (%v).", len(machines), tc.machineCount) } // Verify static IP was set on all machines for _, machine := range machines { provider, success := machine.Spec.ProviderSpec.Value.Object.(*machineapi.VSphereMachineProviderSpec) if !success { t.Errorf("Unable to convert vshere machine provider spec.") } if len(provider.Network.Devices) == 1 { // Check IP if provider.Network.Devices[0].IPAddrs == nil || provider.Network.Devices[0].IPAddrs[0] == "" { t.Errorf("Static ip is not set: %v", machine) } // Check nameserver if provider.Network.Devices[0].Nameservers == nil || provider.Network.Devices[0].Nameservers[0] == "" { t.Errorf("Nameserver is not set: %v", machine) } gateway := provider.Network.Devices[0].Gateway ip, err := netip.ParseAddr(gateway) if err != nil { t.Error(err) } targetGateway := "192.168.101.1" if ip.Is6() { targetGateway = "2001:0db8:85a3:0000:0000:8a2e:0370:7334" } // Check gateway if gateway != targetGateway { t.Errorf("Gateway is incorrect: %v", gateway) } } else { t.Errorf("Devices not set for machine: %v", machine) } } }) } }
package matematica import "testing" // Teste gerado pelo Go func TestMedia(t *testing.T) { t.Parallel() type args struct { numeros []float64 } tests := []struct { name string args args want float64 }{ // TODO: Add test cases. {"teste 1", args{[]float64{7.2, 9.9, 6.1, 5.9}}, 7.28}, {"teste 2", args{[]float64{7.2, 9.9, 6.1, 5.9}}, 7.29}, {"teste 3", args{[]float64{7.2, 9.9, 6.1, 5.9}}, 7.30}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := Media(tt.args.numeros...); got != tt.want { t.Errorf("Media() = %v, want %v", got, tt.want) } }) } } // Teste da aula do curso // const erroPadrao = "Valor esperado %v, mas o resultado encontrado foi %v." // func TestMedia(t *testing.T) { // valorEsperado := 7.28 // valor := Media(7.2, 9.9, 6.1, 5.9) // if valor != valorEsperado { // t.Errorf(erroPadrao, valorEsperado, valor) // } // }
package render import ( "net/http" "testing" "github.com/DungBuiTien1999/bookings/internal/models" ) func TestAddDefaultData(t *testing.T) { var td models.TemplateData req, err := getSession() if err != nil { t.Error(err) } session.Put(req.Context(), "flash", "123") result := AddDefaultData(&td, req) if result.Flash != "123" { t.Error("flash value of 123 not found in session") } } func TestRenderTemplate(t *testing.T) { pathToTemplates = "../../templates" tc, err := CreateTemplateCache() if err != nil { t.Error(err) } app.TemplateCache = tc r, err := getSession() if err != nil { t.Error(err) } ww := myWriter{} err = Template(&ww, r, "home.page.tmpl", &models.TemplateData{}) if err != nil { t.Error("error writing template to browser") } err = Template(&ww, r, "no-existent.page.tmpl", &models.TemplateData{}) if err == nil { t.Error("rendered template that does not exit") } } func TestNewTemplates(t *testing.T) { NewRenderer(app) } func TestCreateTemplateCache(t *testing.T) { pathToTemplates = "../../templates" _, err := CreateTemplateCache() if err != nil { t.Error(err) } } func getSession() (*http.Request, error) { req, err := http.NewRequest("GET", "/some-url", nil) if err != nil { return nil, err } ctx := req.Context() ctx, _ = session.Load(ctx, req.Header.Get("X-Session")) req = req.WithContext(ctx) return req, nil }
package header import "github.com/imulab/coldcall" const ( KeyAccept = "KeyAccept" ) // Accept sets the given contentType as the "KeyAccept" header on the http.Request. func Accept(contentType string) coldcall.Option { return Custom(KeyAccept, contentType) }
package main import ( "fmt" ) // 429. N叉树的层序遍历 // 给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。 // https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/ func main() { tree := &Node{ Val: 1, Children: []*Node{ {3, []*Node{ {5, nil}, {6, nil}, }}, {2, nil}, {4, nil}, }, } fmt.Println(levelOrder(tree)) fmt.Println(levelOrder2(tree)) } type Node struct { Val int Children []*Node } // 法一:利用队列,循环 func levelOrder(root *Node) (result [][]int) { if root == nil { return nil } queue := []*Node{root} for len(queue) != 0 { n := len(queue) // 本层节点数量 val := []int{} // 本层节点值 for i := 0; i < n; i++ { val = append(val, queue[i].Val) if queue[i].Children != nil { queue = append(queue, queue[i].Children...) } } queue = queue[n:] result = append(result, val) } return } // 法二:递归,增加level参数表示层级 func levelOrder2(root *Node) (result [][]int) { if root == nil { return nil } helper(root, 0, &result) return } func helper(root *Node, level int, result *[][]int) { if len(*result) <= level { *result = append(*result, []int{}) } (*result)[level] = append((*result)[level], root.Val) for _, child := range root.Children { helper(child, level+1, result) } }
package subprocess import ( "context" "fmt" "log" "os/exec" "github.com/egnyte/ax/pkg/backend/common" "github.com/egnyte/ax/pkg/backend/stream" ) type SubprocessClient struct { command []string } func (client *SubprocessClient) ImplementsAdvancedFilters() bool { return true } func (client *SubprocessClient) Query(ctx context.Context, query common.Query) <-chan common.LogMessage { resultChan := make(chan common.LogMessage) cmd := exec.Command(client.command[0], client.command[1:]...) stdOut, err := cmd.StdoutPipe() if err != nil { log.Printf("Could not get stdout pipe: %v", err) close(resultChan) return resultChan } stdOutStream := stream.New(stdOut) stdErr, err := cmd.StderrPipe() if err != nil { log.Printf("Could not get stderr pipe: %v", err) close(resultChan) return resultChan } stdErrStream := stream.New(stdErr) if err := cmd.Start(); err != nil { fmt.Printf("Could not start process: %s because: %v\n", client.command[0], err) close(resultChan) return resultChan } go func() { stdOutQuery := stdOutStream.Query(ctx, query) stdErrQuery := stdErrStream.Query(ctx, query) stdOutOpen := true stdErrOpen := true for stdOutOpen || stdErrOpen { select { case message, ok := <-stdOutQuery: if !ok { stdOutOpen = false continue } resultChan <- message case message, ok := <-stdErrQuery: if !ok { stdErrOpen = false continue } resultChan <- message case <-ctx.Done(): close(resultChan) cmd.Process.Kill() // Ignoring error, not sure if that's ok // Returning to avoid the Wait() return } } close(resultChan) if err := cmd.Wait(); err != nil { fmt.Printf("Process exited with error: %v\n", err) } }() return resultChan } func New(command []string) *SubprocessClient { return &SubprocessClient{command} } var _ common.Client = &SubprocessClient{}
package logger import ( "github.com/op/go-logging" "os" ) const ( OUTPUT_STD = "stdout" OUTPUT_FILE = "file" OUTPUT_BOTH = "both" ) var Log *logging.Logger func InitLogger(category string, output string, logfile string) { //create a Log = logging.MustGetLogger(category) //define formater var format = logging.MustStringFormatter( "%{color}%{time:15:04:05.000000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}", ) // stdoutBackend := logging.NewLogBackend(os.Stdout, "", 0) stdoutFormater := logging.NewBackendFormatter(stdoutBackend, format) stdoutLevel := logging.AddModuleLevel(stdoutFormater) stdoutLevel.SetLevel(logging.INFO, "") logging.SetBackend(stdoutLevel) }
package podstatus import ( "testing" "github.com/square/p2/pkg/store/consul/statusstore" "github.com/square/p2/pkg/store/consul/statusstore/statusstoretest" "github.com/square/p2/pkg/types" ) func TestSetAndGetStatus(t *testing.T) { store := newFixture() processStatus := ProcessStatus{ EntryPoint: "echo_service", LaunchableID: "some_launchable", LastExit: nil, } testStatus := PodStatus{ ProcessStatuses: []ProcessStatus{ processStatus, }, } podKey := types.NewPodUUID() err := store.Set(podKey, testStatus) if err != nil { t.Fatalf("Unexpected error setting status: %s", err) } status, _, err := store.Get(podKey) if err != nil { t.Fatalf("Unexpected error getting status: %s", err) } if len(status.ProcessStatuses) != 1 { t.Fatalf("Expected one service status entry, but there were %d", len(status.ProcessStatuses)) } if status.ProcessStatuses[0] != processStatus { t.Errorf("Status entry expected to be '%+v', was %+v", processStatus, status.ProcessStatuses[0]) } } func TestDelete(t *testing.T) { store := newFixture() testStatus := PodStatus{ PodStatus: PodLaunched, } // Put a value in the store podKey := types.NewPodUUID() err := store.Set(podKey, testStatus) if err != nil { t.Fatalf("Unexpected error setting status: %s", err) } // Get the value out to confirm it's there status, _, err := store.Get(podKey) if err != nil { t.Fatalf("Unexpected error getting status: %s", err) } if status.PodStatus != PodLaunched { t.Fatalf("expected pod state to be %q but was %q", PodLaunched, status.PodStatus) } // Now delete it err = store.Delete(podKey) if err != nil { t.Fatalf("error deleting pod status: %s", err) } _, _, err = store.Get(podKey) if err == nil { t.Fatal("expected an error fetching a deleted pod status") } if !statusstore.IsNoStatus(err) { t.Errorf("expected error to be NoStatus but was %s", err) } } func TestList(t *testing.T) { store := newFixture() key := types.NewPodUUID() err := store.Set(key, PodStatus{ PodStatus: PodLaunched, }) if err != nil { t.Fatalf("Unable to set up test with an existing key: %s", err) } allStatus, err := store.List() if err != nil { t.Fatalf("unexpected error listing pod status: %s", err) } if len(allStatus) != 1 { t.Fatalf("expected one status record but there were %d", len(allStatus)) } val, ok := allStatus[key] if !ok { t.Fatalf("expected a record for pod %s but there wasn't", key) } if val.PodStatus != PodLaunched { t.Errorf("expected pod status of status record to be %q but was %q", PodLaunched, val.PodStatus) } } func newFixture() *ConsulStore { return &ConsulStore{ statusStore: statusstoretest.NewFake(), namespace: "test_namespace", } }
package crawler type TreeNode struct { Text string `json:"text,omitempty"` Nodes []TreeNode `json:"nodes,omitempty"` } func (t *TreeNode) Add(node TreeNode, indexes []int) { if len(indexes) > 0 { i := indexes[0] for len(t.Nodes) <= i { t.Add(TreeNode{}, []int{}) } t.Nodes[i].Add(node, indexes[1:]) } else { t.Nodes = append(t.Nodes, node) } }
package gui import "github.com/jesseduffield/lazydocker/pkg/gui/panels" func (gui *Gui) intoInterface() panels.IGui { return gui }
package main import "fmt" func main() { /** Print 无换行,不可读取变量,需使用\n进行换行 Println 有换行,不可读取变量 Printf 无换行,可以读取变量,需使用\n进行换行 */ a1 := 1 fmt.Println("这个数字为:%d",a1) fmt.Printf("这个数字为:%d",a1) fmt.Printf("这个数字为:%d\n",a1) fmt.Print("这个数字为:%d",a1) fmt.Print("这个数字为:%d\n",a1) fmt.Println(`用这个符号 你怎么输入的 它怎么输出`) /** 占位符: string %s int %d bool %t 字符 %c 内存地址 %p 通用 %v 除字符及内存地址外 */ s2:="世界" i2:=2019 var b2 bool c2:='a' m2:=100 fmt.Printf("s2:%s,i2:%d,b2:%t,c2:%c,m2:%p\n",s2,i2,b2,c2,&m2) fmt.Printf("s2:%v,i2:%v,b2:%v,c2:%v,m2:%v\n",s2,i2,b2,c2) }
package app import ( "golang.org/x/net/context" "github.com/sirupsen/logrus" "github.com/docker/libcompose/cli/app" "github.com/docker/libcompose/cli/command" "github.com/docker/libcompose/cli/logger" "github.com/docker/libcompose/lookup" "github.com/docker/libcompose/project" "github.com/docker/libcompose/project/options" rLookup "github.com/ouzklcn/rancher-compose/lookup" "github.com/ouzklcn/rancher-compose/rancher" "github.com/ouzklcn/rancher-compose/upgrade" "github.com/urfave/cli" ) type ProjectFactory struct { } type ProjectDeleter struct { } func (p *ProjectFactory) Create(c *cli.Context) (project.APIProject, error) { githubClient, err := rancher.Create(c) if err != nil { return nil, err } err = githubClient.DownloadDockerComposeFile(c.GlobalStringSlice("file"), c.GlobalString("github-docker-file")) if err != nil { return nil, err } err = githubClient.DownloadRancherComposeFile(c.GlobalString("rancher-file"), c.GlobalString("github-rancher-file")) if err != nil { return nil, err } rancherComposeFile, err := rancher.ResolveRancherCompose(c.GlobalString("file"), c.GlobalString("rancher-file")) if err != nil { return nil, err } qLookup, err := rLookup.NewQuestionLookup(rancherComposeFile, &lookup.OsEnvLookup{}) if err != nil { return nil, err } envLookup, err := rLookup.NewFileEnvLookup(c.GlobalString("env-file"), qLookup) if err != nil { return nil, err } ctx := &rancher.Context{ Context: project.Context{ ResourceLookup: &rLookup.FileResourceLookup{}, EnvironmentLookup: envLookup, LoggerFactory: logger.NewColorLoggerFactory(), }, RancherComposeFile: c.GlobalString("rancher-file"), Url: c.GlobalString("url"), AccessKey: c.GlobalString("access-key"), SecretKey: c.GlobalString("secret-key"), PullCached: c.Bool("cached"), Uploader: &rancher.S3Uploader{}, Args: c.Args(), BindingsFile: c.GlobalString("bindings-file"), } qLookup.Context = ctx command.Populate(&ctx.Context, c) ctx.Upgrade = c.Bool("upgrade") || c.Bool("force-upgrade") ctx.ForceUpgrade = c.Bool("force-upgrade") ctx.Rollback = c.Bool("rollback") ctx.BatchSize = int64(c.Int("batch-size")) ctx.Interval = int64(c.Int("interval")) ctx.ConfirmUpgrade = c.Bool("confirm-upgrade") ctx.Pull = c.Bool("pull") return rancher.NewProject(ctx) } func (p *ProjectDeleter) Delete(c *cli.Context) (error) { githubClient, err := rancher.Create(c) if err != nil { return err } err = githubClient.DownloadDockerComposeFile(c.GlobalStringSlice("file"), c.GlobalString("github-docker-file")) if err != nil { return err } err = githubClient.DownloadRancherComposeFile(c.GlobalString("rancher-file"), c.GlobalString("github-rancher-file")) if err != nil { return err } rancherComposeFile, err := rancher.ResolveRancherCompose(c.GlobalString("file"), c.GlobalString("rancher-file")) if err != nil { return err } qLookup, err := rLookup.NewQuestionLookup(rancherComposeFile, &lookup.OsEnvLookup{}) if err != nil { return err } envLookup, err := rLookup.NewFileEnvLookup(c.GlobalString("env-file"), qLookup) if err != nil { return err } ctx := &rancher.Context{ Context: project.Context{ ResourceLookup: &rLookup.FileResourceLookup{}, EnvironmentLookup: envLookup, LoggerFactory: logger.NewColorLoggerFactory(), }, RancherComposeFile: c.GlobalString("rancher-file"), Url: c.GlobalString("url"), AccessKey: c.GlobalString("access-key"), SecretKey: c.GlobalString("secret-key"), PullCached: c.Bool("cached"), Uploader: &rancher.S3Uploader{}, Args: c.Args(), BindingsFile: c.GlobalString("bindings-file"), } qLookup.Context = ctx command.Populate(&ctx.Context, c) ctx.Upgrade = c.Bool("upgrade") || c.Bool("force-upgrade") ctx.ForceUpgrade = c.Bool("force-upgrade") ctx.Rollback = c.Bool("rollback") ctx.BatchSize = int64(c.Int("batch-size")) ctx.Interval = int64(c.Int("interval")) ctx.ConfirmUpgrade = c.Bool("confirm-upgrade") ctx.Pull = c.Bool("pull") return rancher.DeleteProject(ctx) } func RemoveStack(deleter ProjectDeleter) func(context *cli.Context) error { return func(context *cli.Context) error { err := deleter.Delete(context) if err != nil { logrus.Fatalf("Failed to read project: %v", err) } return err } } func UpgradeCommand(factory app.ProjectFactory) cli.Command { return cli.Command{ Name: "upgrade", Usage: "Perform rolling upgrade between services", Action: app.WithProject(factory, Upgrade), Flags: []cli.Flag{ cli.IntFlag{ Name: "batch-size", Usage: "Number of containers to upgrade at once", Value: 2, }, cli.IntFlag{ Name: "scale", Usage: "Final number of running containers", Value: -1, }, cli.IntFlag{ Name: "interval", Usage: "Update interval in milliseconds", Value: 2000, }, cli.BoolTFlag{ Name: "update-links", Usage: "Update inbound links on target service", }, cli.BoolFlag{ Name: "wait,w", Usage: "Wait for upgrade to complete", }, cli.BoolFlag{ Name: "pull, p", Usage: "Before doing the upgrade do an image pull on all hosts that have the image already", }, cli.BoolFlag{ Name: "cleanup, c", Usage: "Remove the original service definition once upgraded, implies --wait", }, }, } } func RestartCommand(factory app.ProjectFactory) cli.Command { return cli.Command{ Name: "restart", Usage: "Restart services", Action: app.WithProject(factory, app.ProjectRestart), Flags: []cli.Flag{ cli.IntFlag{ Name: "batch-size", Usage: "Number of containers to restart at once", Value: 1, }, cli.IntFlag{ Name: "interval", Usage: "Restart interval in milliseconds", Value: 0, }, }, } } func UpCommand(factory app.ProjectFactory) cli.Command { return cli.Command{ Name: "up", Usage: "Bring all services up", Action: app.WithProject(factory, ProjectUp), Flags: []cli.Flag{ cli.BoolFlag{ Name: "pull, p", Usage: "Before doing the upgrade do an image pull on all hosts that have the image already", }, cli.BoolFlag{ Name: "d", Usage: "Do not block and log", }, cli.BoolFlag{ Name: "upgrade, u, recreate", Usage: "Upgrade if service has changed", }, cli.BoolFlag{ Name: "force-upgrade, force-recreate", Usage: "Upgrade regardless if service has changed", }, cli.BoolFlag{ Name: "confirm-upgrade, c", Usage: "Confirm that the upgrade was success and delete old containers", }, cli.BoolFlag{ Name: "rollback, r", Usage: "Rollback to the previous deployed version", }, cli.IntFlag{ Name: "batch-size", Usage: "Number of containers to upgrade at once", Value: 2, }, cli.IntFlag{ Name: "interval", Usage: "Update interval in milliseconds", Value: 1000, }, }, } } func PullCommand(factory app.ProjectFactory) cli.Command { return cli.Command{ Name: "pull", Usage: "Pulls images for services", Action: app.WithProject(factory, app.ProjectPull), Flags: []cli.Flag{ cli.BoolFlag{ Name: "cached, c", Usage: "Only update hosts that have the image cached, don't pull new", }, }, } } func CreateCommand(factory app.ProjectFactory) cli.Command { return cli.Command{ Name: "create", Usage: "Create all services but do not start", Action: app.WithProject(factory, ProjectCreate), } } func ProjectCreate(p project.APIProject, c *cli.Context) error { if err := p.Create(context.Background(), options.Create{}, c.Args()...); err != nil { return err } // This is to fix circular links... What!? It works. if err := p.Create(context.Background(), options.Create{}, c.Args()...); err != nil { return err } return nil } func ProjectUp(p project.APIProject, c *cli.Context) error { if err := p.Create(context.Background(), options.Create{}, c.Args()...); err != nil { return err } if err := p.Up(context.Background(), options.Up{}, c.Args()...); err != nil { return err } if !c.Bool("d") { p.Log(context.Background(), true) // wait forever <-make(chan interface{}) } return nil } func ProjectDown(p project.APIProject, c *cli.Context) error { err := p.Stop(context.Background(), c.Int("timeout"), c.Args()...) if err != nil { return cli.NewExitError(err.Error(), 1) } err = p.Delete(context.Background(), options.Delete{ RemoveVolume: c.Bool("v"), }, c.Args()...) if err != nil { return cli.NewExitError(err.Error(), 1) } return nil } func Upgrade(p project.APIProject, c *cli.Context) error { args := c.Args() if len(args) != 2 { logrus.Fatalf("Please pass arguments in the form: [from service] [to service]") } err := upgrade.Upgrade(p, args[0], args[1], upgrade.UpgradeOpts{ BatchSize: c.Int("batch-size"), IntervalMillis: c.Int("interval"), FinalScale: c.Int("scale"), UpdateLinks: c.Bool("update-links"), Wait: c.Bool("wait"), CleanUp: c.Bool("cleanup"), Pull: c.Bool("pull"), }) if err != nil { logrus.Fatal(err) } return nil } // StopCommand defines the libcompose stop subcommand. func StopCommand(factory app.ProjectFactory) cli.Command { return cli.Command{ Name: "stop", Usage: "Stop services", Action: app.WithProject(factory, app.ProjectStop), Flags: []cli.Flag{ cli.IntFlag{ Name: "timeout,t", Usage: "Specify a shutdown timeout in seconds.", Value: 10, }, }, } } func DownCommand(factory app.ProjectFactory, deleter ProjectDeleter) cli.Command { return cli.Command{ Name: "down", Usage: "Stop services", Action: app.WithProject(factory, ProjectDown), After: RemoveStack(deleter), Flags: []cli.Flag{ cli.BoolFlag{ Name: "force,f", Usage: "Allow deletion of all services", }, cli.BoolFlag{ Name: "v", Usage: "Remove volumes associated with containers", }, cli.IntFlag{ Name: "timeout,t", Usage: "Specify a shutdown timeout in seconds.", Value: 10, }, }, } }
package functions // Top will return n elements from head of the slice // if the slice has less elements then n that'll return all elements // if n < 0 it'll return empty slice. func (ss SliceType) Top(n int) (top SliceType) { for i := 0; i < len(ss) && n > 0; i++ { top = append(top, ss[i]) n-- } return }
package main import ( "encoding/json" "fmt" "net/http" "os" "strings" ) const cacheDir string = "./xkcdcache" type ComicInfo struct { Month string Num int Link string Year string News string SafeTitle string `json:"safe_title"` Transcript string Alt string Img string Title string Day string } func getLatestComic() (*ComicInfo, error) { latestComicURL := "http://xkcd.com/info.0.json" comic, err := fetchComicFromURL(latestComicURL) return comic, err } func getComic(id int) (*ComicInfo, error) { comicURL := fmt.Sprintf("http://xkcd.com/%d/info.0.json", id) return fetchComicFromURL(comicURL) } func fetchComicFromURL(url string) (*ComicInfo, error) { resp, err := http.Get(url) if err != nil { return nil, err } if resp.StatusCode != 200 { resp.Body.Close() return nil, fmt.Errorf("failed to fetch %s with status code %d", url, resp.StatusCode) } var result ComicInfo if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { resp.Body.Close() return nil, err } resp.Body.Close() return &result, nil } func fetchAndCacheComic(id int, query string) { cacheLocation := fmt.Sprintf("%s/%d.json", cacheDir, id) file, err := os.Open(cacheLocation) var comic *ComicInfo = new(ComicInfo) if err != nil { comic, err = getComic(id) if err != nil { fmt.Fprintf(os.Stderr, "error while fetching %d: %s\n", id, err) return } writeFile, err := os.Create(cacheLocation) if err != nil { fmt.Fprintf(os.Stderr, "error while writing to cache <%s> for %d: %s\n", cacheLocation, id, err) return } json.NewEncoder(writeFile).Encode(comic) writeFile.Close() return } else { json.NewDecoder(file).Decode(comic) } file.Close() if comic != nil && (strings.Contains(strings.ToLower(comic.Transcript), query) || strings.Contains(strings.ToLower(comic.Alt), query)) { fmt.Printf("[#%d]\thttps://xkcd.com/%d\t%s\n", comic.Num, comic.Num, comic.Alt) } } func cacheAndSearchComics(query string) error { comic, err := getLatestComic() if err != nil { return err } latest := comic.Num for i := 1; i <= latest; i++ { fetchAndCacheComic(i, query) } return nil } func main() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Need a search argument") } query := os.Args[1] err := cacheAndSearchComics(query) if err != nil { fmt.Fprintf(os.Stderr, "Failed with %s", err) } }
package goreq import ( "fmt" "github.com/stretchr/testify/assert" "net/http" "net/url" "testing" ) func TestRawResp(t *testing.T) { var resp http.Response var bodyBytes []byte err := Get("https://httpbin.org/get", RawResp(&resp, &bodyBytes)).Do() assert.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, int(resp.ContentLength), len(bodyBytes)) err = Post("https://httpbin.org/post", RawResp(&resp, &bodyBytes)).Do() assert.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, int(resp.ContentLength), len(bodyBytes)) err = Delete("https://httpbin.org/delete", RawResp(&resp, &bodyBytes)).Do() assert.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, int(resp.ContentLength), len(bodyBytes)) err = Put("https://httpbin.org/put", RawResp(&resp, &bodyBytes)).Do() assert.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, int(resp.ContentLength), len(bodyBytes)) err = Patch("https://httpbin.org/patch", RawResp(&resp, &bodyBytes)).Do() assert.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, int(resp.ContentLength), len(bodyBytes)) } func TestAllowStatusCodes(t *testing.T) { err := Get("https://httpbin.org/get", ExpectedStatusCodes([]int{http.StatusFound})).Do() assert.NotNil(t, err) } type HttpBinResp struct { Headers map[string]string `json:"headers"` Data string `json:"data"` Json interface{} `json:"json"` Form interface{} `json:"form"` } type JsonRequest struct { String string Int int } func TestJsonReqResp(t *testing.T) { req := JsonRequest{ String: "hello", Int: 666, } respBody := JsonRequest{} resp := HttpBinResp{ Json: &respBody, } err := Post("https://httpbin.org/post", JsonReq(req), JsonResp(&resp)).Do() assert.NoError(t, err) assert.Equal(t, req, respBody) } func TestFormReq(t *testing.T) { req := url.Values{ "key1": []string{"v1"}, "key2": []string{"vv1", "vv2"}, } resp := HttpBinResp{} err := Post("https://httpbin.org/post", FormReq(req), JsonResp(&resp)).Do() assert.NoError(t, err) assert.Equal(t, map[string]interface{}{ "key1": "v1", "key2": []interface{}{ "vv1", "vv2", }, }, resp.Form) } type CountResultWrapper struct { Headers map[string]string `json:"headers"` Data string `json:"data"` Json interface{} `json:"json"` doValidationCallback func() int returnOkAfterRequests int } func (w *CountResultWrapper) SetData(ret interface{}) { w.Json = ret } func (w *CountResultWrapper) Validate() error { count := w.doValidationCallback() if count == w.returnOkAfterRequests { return nil } return fmt.Errorf("%d request is expected failed", count) } func TestRetryAndValidation(t *testing.T) { req := JsonRequest{ String: "hello", Int: 666, } respData := JsonRequest{} callCount := 0 cb := func() int { callCount++ return callCount } err := Post("https://httpbin.org/post", JsonReq(req), JsonResp(&respData), RespWrapper(&CountResultWrapper{returnOkAfterRequests: 2, doValidationCallback: cb}), Retry(&RetryOpt{ Attempts: 2, }), ).Do() assert.NoError(t, err) assert.Equal(t, req, respData) callCount = 0 err = Post("https://httpbin.org/post", JsonReq(req), JsonResp(&respData), RespWrapper(&CountResultWrapper{returnOkAfterRequests: 2, doValidationCallback: cb}), Retry(&RetryOpt{ Attempts: 1, }), ).Do() assert.NotNil(t, err) }
package model import ( "database/sql" "encoding/base64" "encoding/hex" "encoding/json" "strings" "time" "github.com/go-webauthn/webauthn/protocol" "github.com/go-webauthn/webauthn/webauthn" "github.com/google/uuid" "gopkg.in/yaml.v3" ) const ( attestationTypeFIDOU2F = "fido-u2f" ) // WebAuthnUser is an object to represent a user for the WebAuthn lib. type WebAuthnUser struct { ID int `db:"id"` RPID string `db:"rpid"` Username string `db:"username"` UserID string `db:"userid"` DisplayName string `db:"-"` Devices []WebAuthnDevice `db:"-"` } // HasFIDOU2F returns true if the user has any attestation type `fido-u2f` devices. func (w WebAuthnUser) HasFIDOU2F() bool { for _, c := range w.Devices { if c.AttestationType == attestationTypeFIDOU2F { return true } } return false } // WebAuthnID implements the webauthn.User interface. func (w WebAuthnUser) WebAuthnID() []byte { return []byte(w.UserID) } // WebAuthnName implements the webauthn.User interface. func (w WebAuthnUser) WebAuthnName() string { return w.Username } // WebAuthnDisplayName implements the webauthn.User interface. func (w WebAuthnUser) WebAuthnDisplayName() string { return w.DisplayName } // WebAuthnIcon implements the webauthn.User interface. func (w WebAuthnUser) WebAuthnIcon() string { return "" } // WebAuthnCredentials implements the webauthn.User interface. func (w WebAuthnUser) WebAuthnCredentials() (credentials []webauthn.Credential) { credentials = make([]webauthn.Credential, len(w.Devices)) var credential webauthn.Credential for i, device := range w.Devices { aaguid, err := device.AAGUID.MarshalBinary() if err != nil { continue } credential = webauthn.Credential{ ID: device.KID.Bytes(), PublicKey: device.PublicKey, AttestationType: device.AttestationType, Authenticator: webauthn.Authenticator{ AAGUID: aaguid, SignCount: device.SignCount, CloneWarning: device.CloneWarning, }, } transports := strings.Split(device.Transport, ",") credential.Transport = []protocol.AuthenticatorTransport{} for _, t := range transports { if t == "" { continue } credential.Transport = append(credential.Transport, protocol.AuthenticatorTransport(t)) } credentials[i] = credential } return credentials } // WebAuthnCredentialDescriptors decodes the users credentials into protocol.CredentialDescriptor's. func (w WebAuthnUser) WebAuthnCredentialDescriptors() (descriptors []protocol.CredentialDescriptor) { credentials := w.WebAuthnCredentials() descriptors = make([]protocol.CredentialDescriptor, len(credentials)) for i, credential := range credentials { descriptors[i] = credential.Descriptor() } return descriptors } // NewWebAuthnDeviceFromCredential creates a WebAuthnDevice from a webauthn.Credential. func NewWebAuthnDeviceFromCredential(rpid, username, description string, credential *webauthn.Credential) (device WebAuthnDevice) { transport := make([]string, len(credential.Transport)) for i, t := range credential.Transport { transport[i] = string(t) } device = WebAuthnDevice{ RPID: rpid, Username: username, CreatedAt: time.Now(), Description: description, KID: NewBase64(credential.ID), AttestationType: credential.AttestationType, Transport: strings.Join(transport, ","), SignCount: credential.Authenticator.SignCount, CloneWarning: credential.Authenticator.CloneWarning, PublicKey: credential.PublicKey, } aaguid, err := uuid.Parse(hex.EncodeToString(credential.Authenticator.AAGUID)) if err == nil { device.AAGUID = NullUUID(aaguid) } return device } // WebAuthnDevice represents a WebAuthn Device in the database storage. type WebAuthnDevice struct { ID int `db:"id"` CreatedAt time.Time `db:"created_at"` LastUsedAt sql.NullTime `db:"last_used_at"` RPID string `db:"rpid"` Username string `db:"username"` Description string `db:"description"` KID Base64 `db:"kid"` AAGUID uuid.NullUUID `db:"aaguid"` AttestationType string `db:"attestation_type"` Transport string `db:"transport"` SignCount uint32 `db:"sign_count"` CloneWarning bool `db:"clone_warning"` PublicKey []byte `db:"public_key"` } // UpdateSignInInfo adjusts the values of the WebAuthnDevice after a sign in. func (d *WebAuthnDevice) UpdateSignInInfo(config *webauthn.Config, now time.Time, signCount uint32) { d.LastUsedAt = sql.NullTime{Time: now, Valid: true} d.SignCount = signCount if d.RPID != "" { return } switch d.AttestationType { case attestationTypeFIDOU2F: d.RPID = config.RPOrigin default: d.RPID = config.RPID } } // DataValueLastUsedAt provides LastUsedAt as a *time.Time instead of sql.NullTime. func (d *WebAuthnDevice) DataValueLastUsedAt() *time.Time { if d.LastUsedAt.Valid { value := time.Unix(d.LastUsedAt.Time.Unix(), int64(d.LastUsedAt.Time.Nanosecond())) return &value } return nil } // DataValueAAGUID provides AAGUID as a *string instead of uuid.NullUUID. func (d *WebAuthnDevice) DataValueAAGUID() *string { if d.AAGUID.Valid { value := d.AAGUID.UUID.String() return &value } return nil } func (d *WebAuthnDevice) ToData() WebAuthnDeviceData { o := WebAuthnDeviceData{ ID: d.ID, CreatedAt: d.CreatedAt, LastUsedAt: d.DataValueLastUsedAt(), RPID: d.RPID, Username: d.Username, Description: d.Description, KID: d.KID.String(), AAGUID: d.DataValueAAGUID(), AttestationType: d.AttestationType, SignCount: d.SignCount, CloneWarning: d.CloneWarning, PublicKey: base64.StdEncoding.EncodeToString(d.PublicKey), } if d.Transport != "" { o.Transports = strings.Split(d.Transport, ",") } return o } // MarshalJSON returns the WebAuthnDevice in a JSON friendly manner. func (d *WebAuthnDevice) MarshalJSON() (data []byte, err error) { return json.Marshal(d.ToData()) } // MarshalYAML marshals this model into YAML. func (d *WebAuthnDevice) MarshalYAML() (any, error) { return d.ToData(), nil } // UnmarshalYAML unmarshalls YAML into this model. func (d *WebAuthnDevice) UnmarshalYAML(value *yaml.Node) (err error) { o := &WebAuthnDeviceData{} if err = value.Decode(o); err != nil { return err } if d.PublicKey, err = base64.StdEncoding.DecodeString(o.PublicKey); err != nil { return err } var aaguid uuid.UUID if o.AAGUID != nil { if aaguid, err = uuid.Parse(*o.AAGUID); err != nil { return err } d.AAGUID = NullUUID(aaguid) } var kid []byte if kid, err = base64.StdEncoding.DecodeString(o.KID); err != nil { return err } d.KID = NewBase64(kid) d.CreatedAt = o.CreatedAt d.RPID = o.RPID d.Username = o.Username d.Description = o.Description d.AttestationType = o.AttestationType d.Transport = strings.Join(o.Transports, ",") d.SignCount = o.SignCount d.CloneWarning = o.CloneWarning if o.LastUsedAt != nil { d.LastUsedAt = sql.NullTime{Valid: true, Time: *o.LastUsedAt} } return nil } // WebAuthnDeviceData represents a WebAuthn Device in the database storage. type WebAuthnDeviceData struct { ID int `json:"id" yaml:"-"` CreatedAt time.Time `yaml:"created_at" json:"created_at" jsonschema:"title=Created At" jsonschema_description:"The time this device was created"` LastUsedAt *time.Time `yaml:"last_used_at,omitempty" json:"last_used_at,omitempty" jsonschema:"title=Last Used At" jsonschema_description:"The last time this device was used"` RPID string `yaml:"rpid" json:"rpid" jsonschema:"title=Relying Party ID" jsonschema_description:"The Relying Party ID used to register this device"` Username string `yaml:"username" json:"username" jsonschema:"title=Username" jsonschema_description:"The username of the user this device belongs to"` Description string `yaml:"description" json:"description" jsonschema:"title=Description" jsonschema_description:"The user description of this device"` KID string `yaml:"kid" json:"kid" jsonschema:"title=Public Key ID" jsonschema_description:"The Public Key ID of this device"` AAGUID *string `yaml:"aaguid,omitempty" json:"aaguid,omitempty" jsonschema:"title=AAGUID" jsonschema_description:"The Authenticator Attestation Global Unique Identifier of this device"` AttestationType string `yaml:"attestation_type" json:"attestation_type" jsonschema:"title=Attestation Type" jsonschema_description:"The attestation format type this device uses"` Transports []string `yaml:"transports" json:"transports" jsonschema:"title=Transports" jsonschema_description:"The last recorded device transports"` SignCount uint32 `yaml:"sign_count" json:"sign_count" jsonschema:"title=Sign Count" jsonschema_description:"The last recorded device sign count"` CloneWarning bool `yaml:"clone_warning" json:"clone_warning" jsonschema:"title=Clone Warning" jsonschema_description:"The clone warning status of the device"` PublicKey string `yaml:"public_key" json:"public_key" jsonschema:"title=Public Key" jsonschema_description:"The device public key"` } func (d *WebAuthnDeviceData) ToDevice() (device *WebAuthnDevice, err error) { device = &WebAuthnDevice{ CreatedAt: d.CreatedAt, RPID: d.RPID, Username: d.Username, Description: d.Description, AttestationType: d.AttestationType, Transport: strings.Join(d.Transports, ","), SignCount: d.SignCount, CloneWarning: d.CloneWarning, } if device.PublicKey, err = base64.StdEncoding.DecodeString(d.PublicKey); err != nil { return nil, err } var aaguid uuid.UUID if d.AAGUID != nil { if aaguid, err = uuid.Parse(*d.AAGUID); err != nil { return nil, err } device.AAGUID = NullUUID(aaguid) } var kid []byte if kid, err = base64.StdEncoding.DecodeString(d.KID); err != nil { return nil, err } device.KID = NewBase64(kid) if d.LastUsedAt != nil { device.LastUsedAt = sql.NullTime{Valid: true, Time: *d.LastUsedAt} } return device, nil } // WebAuthnDeviceExport represents a WebAuthnDevice export file. type WebAuthnDeviceExport struct { WebAuthnDevices []WebAuthnDevice `yaml:"webauthn_devices"` } // WebAuthnDeviceDataExport represents a WebAuthnDevice export file. type WebAuthnDeviceDataExport struct { WebAuthnDevices []WebAuthnDeviceData `yaml:"webauthn_devices" json:"webauthn_devices" jsonschema:"title=WebAuthn Devices" jsonschema_description:"The list of WebAuthn devices"` } // ToData converts this WebAuthnDeviceExport into a WebAuthnDeviceDataExport. func (export WebAuthnDeviceExport) ToData() WebAuthnDeviceDataExport { data := WebAuthnDeviceDataExport{ WebAuthnDevices: make([]WebAuthnDeviceData, len(export.WebAuthnDevices)), } for i, device := range export.WebAuthnDevices { data.WebAuthnDevices[i] = device.ToData() } return data } // MarshalYAML marshals this model into YAML. func (export WebAuthnDeviceExport) MarshalYAML() (any, error) { return export.ToData(), nil }
/* * EVE Swagger Interface * * An OpenAPI for EVE Online * * OpenAPI spec version: 0.4.1.dev1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ package swagger // ally object type GetWarsWarIdAlly struct { // Alliance ID if and only if this ally is an alliance AllianceId int32 `json:"alliance_id,omitempty"` // Corporation ID if and only if this ally is a corporation CorporationId int32 `json:"corporation_id,omitempty"` }
package common import ( "encoding/json" "fmt" "github.com/garyburd/redigo/redis" "time" ) type RedisConfig struct { Host string `json:"host"` Port int32 `json:"port"` MaxIdle int32 `json:"max_idle"` IdleTimeout int32 `json:"idle_timeout"` MaxActive int32 `json:"max_active"` } func NewRedisConf(m json.RawMessage) (conf *RedisConfig, err error) { conf = &RedisConfig{} err = json.Unmarshal(m, conf) return } func RedisPoolForCfg(cfg *RedisConfig) (pool *redis.Pool, err error) { dataSourceName := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port) //connect pool = &redis.Pool{ MaxIdle: int(cfg.MaxIdle), IdleTimeout: 240 * time.Second, Dial: func() (redis.Conn, error) { fmt.Println("redis connect " + dataSourceName) c, err := redis.Dial("tcp", dataSourceName) if err != nil { panic(err.Error()) } return c, err }, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do("PING") return err }, } return } func NewRedisService(m json.RawMessage) (rs *RedisService, err error) { conf, err1 := NewRedisConf(m) if err1 != nil { err = err1 return } rs = &RedisService{RedisCfg: conf} return } type RedisService struct { RedisCfg *RedisConfig RedisPool *redis.Pool } func (r *RedisService) Init() { pool, err := RedisPoolForCfg(r.RedisCfg) dataSourceName := fmt.Sprintf("%s:%d", r.RedisCfg.Host, r.RedisCfg.Port) if err != nil { panic("init redis service failed:" + err.Error()) } r.RedisPool = pool logger.Printf("connect %s success\n", dataSourceName) } func (r *RedisService) AfterInit() { } func (r *RedisService) BeforeDestroy() { } func (r *RedisService) Destroy() { }
package db import ( . "gopkg.in/check.v1" "testing" ) // IF USING test framework, need a file like this in each package=directory. func Test(t *testing.T) { TestingT(t) } type XLSuite struct{} var _ = Suite(&XLSuite{}) const ( BLOCK_SIZE = 4096 SHA1_LEN = 20 SHA3_LEN = 32 VERBOSITY = 1 )
package main func reverseKGroup(head *ListNode, k int) *ListNode { dummyHead := &ListNode{} dummyHead.Next = head pre := dummyHead cur := head next := &ListNode{} len := 0 for head != nil { len++ head = head.Next } head = dummyHead.Next //1->2->3 先反转成2->1->3 载反转成3->2-1,此时相当于2-1是一个整体 for i := 0; i < len/k; i++ { // 一组k循环 for j := 0; j < k-1; j++ { next = cur.Next cur.Next = next.Next next.Next = pre.Next pre.Next = next } // 更新进行下一组次反转 pre = cur cur = cur.Next } return dummyHead.Next }
package config import ( "github.com/caarlos0/env" "log" ) type CommonEnvConfigs struct { // Logging level LogLevel string `json:"LOG_LEVEL" env:"LOG_LEVEL" envDefault:"debug"` // Service configs ServiceName string `json:"SERVICE_NAME" env:"SERVICE_NAME" envDefault:"vk-scrapper"` // Server configs ServerPort string `json:"SERVER_PORT" env:"SERVER_PORT" envDefault:"8082"` // PostgreSQL configs PostgresDBStr string `json:"POSTGRES_DB_STR" env:"POSTGRES_DB_STR" envDefault:"postgresql://postgres:postgres@128.199.77.142:5432/vk_users"` // VK configs VkAppID int `json:"VK_APP_ID" env:"VK_APP_ID"` VkPrivateKey string `json:"VK_PRIVATE_KEY" env:"VK_PRIVATE_KEY"` VkServiceToken string `json:"VK_SERVICE_TOKEN" env:"VK_SERVICE_TOKEN"` VKClientToken string `json:"VK_CLIENT_TOKEN" env:"VK_CLIENT_TOKEN"` } func GetCommonEnvConfigs() CommonEnvConfigs { envConfig := CommonEnvConfigs{} err := env.Parse(&envConfig) if err != nil { log.Panicf("Error parse env config:%s", err) return envConfig } return envConfig }
package models import ( "encoding/json" "fmt" "github.com/PuerkitoBio/goquery" "log" "net/url" ) const ( XINSEHNG_URL_PREFIX = "http://xinsheng.huawei.com/cn/index.php?app=search&mod=Forum&act=index&cTime=1&key=" ) type ForumInfo struct { Title string `json:"title"` Href string `json:"href"` Info string `json:"info"` } func (info ForumInfo) String() string { body, err := json.Marshal(info) if err != nil { log.Fatal(err) } return string(body) } func ParseForum(query string) *[]ForumInfo { url := fmt.Sprintf("%s%s", XINSEHNG_URL_PREFIX, url.QueryEscape(query)) doc, err := goquery.NewDocument(url) if err != nil { log.Println(err) return nil } infoArray := []ForumInfo{} doc.Find("LI").Each(func(i int, li *goquery.Selection) { title := li.Find(".title") a := title.Find("A") if href, exist := a.Attr("href"); exist { infoArray = append(infoArray, ForumInfo{a.Text(), href, li.Find(".info").Text()}) } }) return &infoArray }
package main import ( "fmt" "math/big" ) func main() { var n int fmt.Scanf("%d", &n) for i := 0; i < n; i++ { var x int64 _, err := fmt.Scanf("%d", &x) if err != nil { break } x++ if x%2 == 0 || x%7 != 0 { fmt.Println("No") continue } i := big.NewInt(x + 2) isPrime := i.ProbablyPrime(1) if isPrime { fmt.Println("Yes") } else { fmt.Println("No") } } }
// fzfutil is to use fzf as library package fzfutil import ( "io" "os" "os/exec" "strings" ) // Based on, https://junegunn.kr/2016/02/using-fzf-in-your-program func FZF(input func(in io.WriteCloser), opts ...string) ([]string, error) { fzf, err := exec.LookPath("fzf") if err != nil { return nil, err } cmd := exec.Command(fzf, opts...) cmd.Stderr = os.Stderr in, _ := cmd.StdinPipe() go func() { input(in) in.Close() }() stdout, err := cmd.Output() if err != nil { exitError, ok := err.(*exec.ExitError) if !ok { return nil, err } else { code := exitError.ExitCode() // EXIT STATUS // 0 Normal exit // 1 No match // 2 Error // 130 Interrupted with CTRL-C or ESC if code == 1 || code == 130 { return nil, nil } } } return strings.Split(string(stdout), "\n"), nil }
package autonat import ( "context" "net" "testing" "time" pstore "gx/ipfs/QmQFFp4ntkd4C14sP3FaH9WJyBuetuGUVo6dShNHvnoEvC/go-libp2p-peerstore" libp2p "gx/ipfs/QmSgtf5vHyugoxcwMbyNy6bZ9qPDDTJSYEED2GkWjLwitZ/go-libp2p" manet "gx/ipfs/QmZcLBXKaFe8ND5YHPkJRAwmhJGrVsi1JqDZNyJ4nRK5Mj/go-multiaddr-net" autonat "gx/ipfs/QmZgrJk2k14P3zHUAz4hdk1TnU57iaTWEk8fGmFkrafEMX/go-libp2p-autonat" host "gx/ipfs/QmfRHxh8bt4jWLKRhNvR5fn7mFACrQBFLqV4wyoymEExKV/go-libp2p-host" ) func makeAutoNATService(ctx context.Context, t *testing.T) (host.Host, *AutoNATService) { h, err := libp2p.New(ctx, libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0")) if err != nil { t.Fatal(err) } as, err := NewAutoNATService(ctx, h) if err != nil { t.Fatal(err) } return h, as } func makeAutoNATClient(ctx context.Context, t *testing.T) (host.Host, autonat.AutoNATClient) { h, err := libp2p.New(ctx, libp2p.ListenAddrStrings("/ip4/127.0.0.1/tcp/0")) if err != nil { t.Fatal(err) } cli := autonat.NewAutoNATClient(h, nil) return h, cli } func connect(t *testing.T, a, b host.Host) { pinfo := pstore.PeerInfo{ID: a.ID(), Addrs: a.Addrs()} err := b.Connect(context.Background(), pinfo) if err != nil { t.Fatal(err) } } // Note: these tests assume that the host has only private inet addresses! func TestAutoNATServiceDialError(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() save := AutoNATServiceDialTimeout AutoNATServiceDialTimeout = 1 * time.Second hs, _ := makeAutoNATService(ctx, t) hc, ac := makeAutoNATClient(ctx, t) connect(t, hs, hc) _, err := ac.DialBack(ctx, hs.ID()) if err == nil { t.Fatal("Dial back succeeded unexpectedly!") } if !autonat.IsDialError(err) { t.Fatal(err) } AutoNATServiceDialTimeout = save } func TestAutoNATServiceDialSuccess(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() save := manet.Private4 manet.Private4 = []*net.IPNet{} hs, _ := makeAutoNATService(ctx, t) hc, ac := makeAutoNATClient(ctx, t) connect(t, hs, hc) _, err := ac.DialBack(ctx, hs.ID()) if err != nil { t.Fatalf("Dial back failed: %s", err.Error()) } manet.Private4 = save } func TestAutoNATServiceDialRateLimiter(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() save1 := AutoNATServiceDialTimeout AutoNATServiceDialTimeout = 1 * time.Second save2 := AutoNATServiceResetInterval AutoNATServiceResetInterval = 1 * time.Second save3 := AutoNATServiceThrottle AutoNATServiceThrottle = 1 save4 := manet.Private4 manet.Private4 = []*net.IPNet{} hs, _ := makeAutoNATService(ctx, t) hc, ac := makeAutoNATClient(ctx, t) connect(t, hs, hc) _, err := ac.DialBack(ctx, hs.ID()) if err != nil { t.Fatal(err) } _, err = ac.DialBack(ctx, hs.ID()) if err == nil { t.Fatal("Dial back succeeded unexpectedly!") } if !autonat.IsDialRefused(err) { t.Fatal(err) } time.Sleep(2 * time.Second) _, err = ac.DialBack(ctx, hs.ID()) if err != nil { t.Fatal(err) } AutoNATServiceDialTimeout = save1 AutoNATServiceResetInterval = save2 AutoNATServiceThrottle = save3 manet.Private4 = save4 }
package neo import ( "github.com/jmcvetta/neoism" "github.com/yggie/github-data-challenge-2014/models" ) func PersistPushEvent(event *models.PushEvent) error { queries := make([]*neoism.CypherQuery, 0) if !CheckExists(EVENTS, event.Id) { query := neoism.CypherQuery{ Statement: `CREATE (:` + string(EVENTS) + ` { id: {id}, type: {type}, created_at: {created_at} })`, Parameters: neoism.Props{ "id": event.Id, "type": event.EventType, "created_at": event.CreatedAt, }, } queries = append(queries, &query) } repository := event.Repository if !CheckExists(REPOSITORIES, repository.Id) { query := &neoism.CypherQuery{ Statement: `CREATE (:` + string(REPOSITORIES) + ` { id: {id}, name: {name}, url: {url} })`, Parameters: neoism.Props{ "id": repository.Id, "name": repository.Name, "url": repository.Url, }, } queries = append(queries, query) distribution := repository.LanguageDistribution() for key, value := range distribution { query = &neoism.CypherQuery{ Statement: ` MATCH (r:` + string(REPOSITORIES) + ` { id: {repository_id} }) CREATE UNIQUE (r)-[:` + string(WRITTEN_IN) + ` { weight: {weight} }]->(:` + string(LANGUAGES) + ` { name: {name} })`, Parameters: neoism.Props{ "repository_id": repository.Id, "name": key, "weight": value, }, } queries = append(queries, query) } } user := event.User if !CheckExists(USERS, user.Id) { query := neoism.CypherQuery{ Statement: `CREATE (:` + string(USERS) + ` { id: {id}, login: {login}, gravatar_id: {gravatar_id}, avatar_url: {avatar_url} })`, Parameters: neoism.Props{ "id": user.Id, "login": user.Login, "gravatar_id": user.GravatarId, "avatar_url": user.AvatarUrl, }, } queries = append(queries, &query) } eventToRepository := neoism.CypherQuery{ Statement: ` MATCH (r:Repository { id: {repository_id} }), (e:Event { id: {event_id} }) CREATE UNIQUE (r)-[:HAS_A]->(e)`, Parameters: neoism.Props{ "event_id": event.Id, "repository_id": repository.Id, }, } queries = append(queries, &eventToRepository) tx, err := db.Begin(queries) if err != nil { return err } err = tx.Commit() if err != nil { err2 := tx.Rollback() if err2 != nil { return err2 } return err } return nil }
package game import ( "github.com/tanema/amore/gfx" ) var colors = map[string]*gfx.Color{ "sky": gfx.NewColor(114, 215, 238, 255), "tree": gfx.NewColor(0, 81, 8, 255), "fog": gfx.NewColor(0, 81, 8, 255), "road": gfx.NewColor(107, 107, 107, 255), "grass": gfx.NewColor(16, 170, 16, 255), "rumble": gfx.NewColor(85, 85, 85, 255), "lane": gfx.NewColor(204, 204, 204, 255), "start": gfx.NewColor(255, 255, 255, 255), "finish": gfx.NewColor(0, 0, 0, 255), }
//go:generate goagen bootstrap -d goabinsample/design package main import ( "goabinsample/app" "github.com/goadesign/goa" "github.com/goadesign/goa/middleware" ) func main() { // Create service service := goa.New("binsample") // Mount middleware service.Use(middleware.RequestID()) service.Use(middleware.LogRequest(true)) service.Use(middleware.ErrorHandler(service, true)) service.Use(middleware.Recover()) // Mount "samples" controller c := NewSamplesController(service) app.MountSamplesController(service, c) // Mount "swagger" controller c2 := NewSwaggerController(service) MountSwaggerController(service, c2) // Start service if err := service.ListenAndServe(":3000"); err != nil { service.LogError("startup", "err", err) } }
// vi:nu:et:sts=4 ts=4 sw=4 // See License.txt in main repository directory // Handle HTTP Events // Generated: 2019-04-24 11:09:33.44631 -0400 EDT m=+0.001906926 package handlers import ( _ "github.com/2kranki/go-sqlite3" "html/template" ) var Tmpls *template.Template func Title(i interface{}) string { return "Title() - NOT Implemented" } func Body(i interface{}) string { return "Body() - NOT Implemented" } func init() { funcs := map[string]interface{}{"Title":Title, "Body":Body,} Tmpls = template.Must(template.New("tmpls").Funcs(funcs).ParseGlob("tmpl/*.tmpl")) }
package main import ( "bufio" "bytes" "encoding/json" "fmt" "io" "io/ioutil" "math/rand" "net" "os" "os/exec" "raft" "strconv" "strings" //"sync" "testing" "time" ) var noOfThreads int = 50 var noOfRequestsPerThread int = 10 //var wgroup sync.WaitGroup var commands []string var procmap map[int]*exec.Cmd var servermap map[int]bool func init() { go launch_servers() time.Sleep(time.Second * 10) } var no_servers int func launch_servers() { fileName := "clusterConfig.json" var obj raft.ClusterConfig file, e := ioutil.ReadFile(fileName) if e != nil { panic("File error: " + e.Error()) } json.Unmarshal(file, &obj) no_servers, _ = strconv.Atoi(obj.Count.Count) procmap = make(map[int]*exec.Cmd) servermap = make(map[int]bool) for i := 1; i <= no_servers; i++ { //wgroup.Add(1) go execute_cmd(i) } //wgroup.Wait() } func execute_cmd(id int) { //fmt.Println("Server Id = ", id) cmd := exec.Command("./bin/kvstore", "-id="+strconv.Itoa(id)) servermap[id] = true cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr //fmt.Println("SErvermap = ", servermap) procmap[id] = cmd err := cmd.Run() if err != nil { //wgroup.Done() } cmd.Wait() //wgroup.Done() } //------------------------------------------------------------------------------------------------------------------- // Helper function to get the ServerId of current leader, using ping to a random server //------------------------------------------------------------------------------------------------------------------ func get_LeaderId(pingServId string) string { //fmt.Println("in leader ") ServAdd := "127.0.0.1:900" + pingServId conn, _ := net.Dial("tcp", ServAdd) //fmt.Println("conn established ") //time.Sleep(5 * time.Second) //fmt.Println("before re ") reader := bufio.NewReader(conn) //fmt.Println("after re ") leaderId := "-1" for leaderId == "-1" { //fmt.Println("in loop ") io.Copy(conn, bytes.NewBufferString("get leaderId\r\n")) resp, _ := reader.ReadBytes('\n') //fmt.Println("resd bytes ") response := strings.Split(strings.TrimSpace(string(resp)), " ") //fmt.Println(string(resp)) if response[0] == "ERRNOTFOUND" { leaderId = pingServId } else if response[0] == "Redirect" && response[3] != "-1" { id, _ := strconv.Atoi(response[3]) if _, ok := servermap[id]; ok { leaderId = response[3] } } } conn.Close() return leaderId } func returnRandServ() int { for k, v := range servermap { if v == true { return k } } return -1 } func killServer(id int) error { if err1 := procmap[id].Process.Kill(); err1 != nil { return err1 //fmt.Println("failed to kill: ", err1) } else { delete(servermap, id) return nil } } func random(min, max int) int { rand.Seed(time.Now().Unix()) return rand.Intn(max-min) + min } //..............................................................................................................................// // Testcase: To test whether multiple clients works together properly. //..............................................................................................................................// func TestMulticlient(t *testing.T) { tester := make(chan int) Serv := get_LeaderId("1") LeaderIdReturned := get_LeaderId(Serv) for i := 0; i < noOfThreads; i++ { go multiclient(t, tester, LeaderIdReturned) } count := 0 for count < noOfThreads { <-tester count += 1 //fmt.Println("test: count is ",count) } if count != noOfThreads { t.Error("TestMulticlient Failed") } else { fmt.Println("Testcase - TestMulticlient : Passed") } } func multiclient(t *testing.T, tester chan int, LeaderIdReturned string) { //Serv := returnRandServ() //LeaderIdReturned := get_LeaderId(strconv.Itoa(Serv)) LeaderAdd := "127.0.0.1:900" + LeaderIdReturned conn, error := net.Dial("tcp", LeaderAdd) if error != nil { conn.Close() } reader := bufio.NewReader(conn) //fmt.Println("test: Giving command connection ",conn) io.Copy(conn, bytes.NewBufferString("set key71 500 2\r\ntj\r\n")) res, err := reader.ReadBytes('\n') //fmt.Println("test: Response: ",res,"connection ",conn ) if err != nil { conn.Close() } else { if strings.Contains(strings.TrimSpace(string(res)), "OK") { tester <- 1 } else { tester <- 0 } } conn.Close() } //..............................................................................................................................// // Testcase to test Leader Election - 1 (First Leader Elect) //..............................................................................................................................// func TestLeaderElect1(t *testing.T) { tester := make(chan bool) go check_LeaderElect1(t, tester) check := <-tester if !check { t.Error("TestLeaderElect1 Failed, please check implementation") } else { fmt.Println("Testcase - TestLeaderElect1 : Passed") } } func check_LeaderElect1(t *testing.T, tester chan bool) { LeaderAdd := "127.0.0.1:900" + get_LeaderId("1") conn, error := net.Dial("tcp", LeaderAdd) if error != nil { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("get LeaderTester\r\n")) reader := bufio.NewReader(conn) resp, error := reader.ReadBytes('\n') if error != nil { conn.Close() } else { response := strings.Split(strings.TrimSpace(string(resp)), " ") if response[0] == "ERRNOTFOUND" { tester <- true } else { tester <- false } } conn.Close() } //..............................................................................................................................// // Testcase to test Basic Set and Get //..............................................................................................................................// func TestSetnGet(t *testing.T) { tester := make(chan bool) go check_SetnGet(t, tester) check := <-tester if !check { t.Error("SetnGet Failed, please check implementation") } else { fmt.Println("Testcase - TestSetnGet : Passed") } } func check_SetnGet(t *testing.T, tester chan bool) { time.Sleep(time.Second * 3) LeaderAdd := "127.0.0.1:900" + get_LeaderId("1") conn, error := net.Dial("tcp", LeaderAdd) if error != nil { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("set Roll101 50 5\r\nMayur\r\n")) reader := bufio.NewReader(conn) resp, error := reader.ReadBytes('\n') if error != nil { conn.Close() } else { if len(string(resp)) > 0 { response := strings.Split(strings.TrimSpace(string(resp)), " ") if response[0] != "OK" { tester <- false conn.Close() } } else { tester <- false conn.Close() } } io.Copy(conn, bytes.NewBufferString("get Roll101\r\n")) resp, error = reader.ReadBytes('\n') if error != nil { conn.Close() } else { response := strings.Split(strings.TrimSpace(string(resp)), " ") if response[0] == "VALUE" || response[1] == "5" { res, error := reader.ReadString('\n') if error != nil { conn.Close() } else { if res == "Mayur\r\n" { tester <- true conn.Close() } else { tester <- false conn.Close() } } } else { tester <- false conn.Close() } } conn.Close() } //..............................................................................................................................// // Testcase to test basic Set and GetM operation //..............................................................................................................................// func TestSetnGETM(t *testing.T) { tester := make(chan bool) go check_SetnGetM(t, tester) check := <-tester if !check { t.Error("SetnGetM Failed, please check implementation") } else { fmt.Println("Testcase - TestSetnGetM : Passed") } } func check_SetnGetM(t *testing.T, tester chan bool) { LeaderAdd := "127.0.0.1:900" + get_LeaderId("1") conn, error := net.Dial("tcp", LeaderAdd) if error != nil { tester <- false conn.Close() } reader := bufio.NewReader(conn) io.Copy(conn, bytes.NewBufferString("set Roll102 50 9\r\nTarunjain\r\n")) resp, err := reader.ReadBytes('\n') io.Copy(conn, bytes.NewBufferString("set Roll102 500 9\r\njainTarun\r\n")) resp, err = reader.ReadBytes('\n') io.Copy(conn, bytes.NewBufferString("getm Roll102\r\n")) resp, err = reader.ReadBytes('\n') res := string(resp) //fmt.Println(res) if err != nil { tester <- false conn.Close() } else { res = strings.TrimRight(string(res), "\r\n") //fmt.Println(res) response := strings.Split(strings.TrimSpace(res), " ") if len(response) == 4 && response[0] == "VALUE" { res, err = reader.ReadString('\n') if err != nil && res != "jainTarun\r\n" { tester <- false conn.Close() } else { tester <- true conn.Close() } } else { tester <- true conn.Close() } } conn.Close() } //..............................................................................................................................// // Testcase: To test error conditions //..............................................................................................................................// func TestCheckError(t *testing.T) { tester := make(chan bool) go check_error(t, tester) check := <-tester if !check { t.Error("TestCheckError Failed, please check implementation") } else { fmt.Println("Testcase - TestCheckError : Passed") } } func check_error(t *testing.T, tester chan bool) { LeaderAdd := "127.0.0.1:900" + get_LeaderId("1") conn, error := net.Dial("tcp", LeaderAdd) if error != nil { tester <- false conn.Close() } reader := bufio.NewReader(conn) io.Copy(conn, bytes.NewBufferString("set\r\n")) res, err := reader.ReadBytes('\n') if err != nil || string(res) != "ERRCMDERR\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("set key\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRCMDERR\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("set key abc 4\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRCMDERR\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("set keysgbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb 10 4\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRCMDERR\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("set key 10 4 noreply\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRCMDERR\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("set key 10 4\r\n")) io.Copy(conn, bytes.NewBufferString("abcdef\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRCMDERR\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("get\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRCMDERR\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("get 101\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRNOTFOUND\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("getm\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRCMDERR\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("getm 101\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRNOTFOUND\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("cas\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRCMDERR\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("set ROLL1 50 2\r\ntj\r\n")) res, err = reader.ReadBytes('\n') io.Copy(conn, bytes.NewBufferString("cas ROLL1 500 1 5\r\nabcde\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERR_VERSION\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("cas ROLL2 500 1 5\r\nabcde\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRNOTFOUND\r\n" { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("delete ROLL2\r\n")) res, err = reader.ReadBytes('\n') if err != nil || string(res) != "ERRNOTFOUND\r\n" { tester <- false conn.Close() } tester <- true conn.Close() } //..............................................................................................................................// // Testcase: To test error condition of Error-Redirect and all servers redirect to same server : Leader //..............................................................................................................................// func TestCheckErrorRedirect(t *testing.T) { tester := make(chan bool) go check_errorRedirect(t, tester) check := <-tester if !check { t.Error("TestCheckErrorRedirect Failed, please check implementation") } else { fmt.Println("Testcase - TestCheckErrorRedirect : Passed") } } func check_errorRedirect(t *testing.T, tester chan bool) { LeaderId := get_LeaderId("1") slice := []string{"2", "3", "4", "5"} for _, elem := range slice { if LeaderId != get_LeaderId(elem) { tester <- false break } else { tester <- true } } } //..............................................................................................................................// //Testcase to test basic Set and Expiray //..............................................................................................................................// func TestSetnExp(t *testing.T) { tester := make(chan bool) go check_SetnExp(t, tester) check := <-tester if !check { t.Error("SetnExpiray Failed, please check implementation") } else { fmt.Println("Testcase - TestSetnExpiary : Passed") } } func check_SetnExp(t *testing.T, tester chan bool) { LeaderAdd := "127.0.0.1:900" + get_LeaderId("1") conn, error := net.Dial("tcp", LeaderAdd) if error != nil { tester <- false conn.Close() } reader := bufio.NewReader(conn) io.Copy(conn, bytes.NewBufferString("set Roll104 5 3\r\nTj1\r\n")) res, err := reader.ReadBytes('\n') io.Copy(conn, bytes.NewBufferString("set Roll105 10 3\r\nTj2\r\n")) res, err = reader.ReadBytes('\n') io.Copy(conn, bytes.NewBufferString("set Roll106 15 3\r\nTj3\r\n")) res, err = reader.ReadBytes('\n') time.Sleep(time.Second * 6) io.Copy(conn, bytes.NewBufferString("getm Roll104\r\n")) res, err = reader.ReadBytes('\n') if err == nil && string(res) == "ERRNOTFOUND\r\n" { io.Copy(conn, bytes.NewBufferString("getm Roll105\r\n")) res, err = reader.ReadBytes('\n') if err != nil { tester <- false conn.Close() } else { resp := strings.TrimRight(string(res), "\r\n") //fmt.Println(res) response := strings.Split(strings.TrimSpace(resp), " ") if len(response) == 4 && response[0] == "VALUE" { res, err = reader.ReadBytes('\n') if err != nil && string(res) != "Tj2\r\n" { tester <- false conn.Close() } else { time.Sleep(time.Second * 11) io.Copy(conn, bytes.NewBufferString("getm Roll106\r\n")) res1, err1 := reader.ReadBytes('\n') io.Copy(conn, bytes.NewBufferString("delete Roll105\r\n")) res2, err2 := reader.ReadBytes('\n') if err1 == nil && err2 == nil && string(res1) == "ERRNOTFOUND\r\n" && string(res2) == "ERRNOTFOUND\r\n" { tester <- true conn.Close() } else { tester <- false conn.Close() } } } else { tester <- false conn.Close() } } } else { tester <- false conn.Close() } conn.Close() } //..............................................................................................................................// //Testcase to test basic Set and Cas operation //..............................................................................................................................// func TestSetnCas(t *testing.T) { tester := make(chan bool) go check_SetnCas(t, tester) check := <-tester if !check { t.Error("SetnCas Failed, please check implementation") } else { fmt.Println("Testcase - TestSetnCas : Passed") } } func check_SetnCas(t *testing.T, tester chan bool) { LeaderAdd := "127.0.0.1:900" + get_LeaderId("1") conn, error := net.Dial("tcp", LeaderAdd) if error != nil { tester <- false conn.Close() } reader := bufio.NewReader(conn) io.Copy(conn, bytes.NewBufferString("set Roll103 50 9\r\nTarunjain\r\n")) res, err := reader.ReadBytes('\n') io.Copy(conn, bytes.NewBufferString("cas Roll103 500 0 5\r\nAkash\r\n")) res, err = reader.ReadBytes('\n') io.Copy(conn, bytes.NewBufferString("getm Roll103\r\n")) res, err = reader.ReadBytes('\n') if err != nil { tester <- false conn.Close() } else { resp := strings.TrimRight(string(res), "\r\n") response := strings.Split(strings.TrimSpace(resp), " ") if len(response) == 4 && response[0] == "VALUE" && response[1] == "1" { res, err = reader.ReadBytes('\n') if err != nil && string(res) != "Akash\r\n" { tester <- false conn.Close() } else { io.Copy(conn, bytes.NewBufferString("cas Roll103 500 1 3\r\nAbi\r\n")) res, err := reader.ReadBytes('\n') if err != nil { tester <- false conn.Close() } else { if string(res) == "OK 2\r\n" { tester <- true conn.Close() } else { tester <- false conn.Close() } } } } else { tester <- false conn.Close() } } conn.Close() } //..............................................................................................................................// //Testcase to test basic Set and Delete operation //..............................................................................................................................// func TestSetnDel(t *testing.T) { tester := make(chan bool) go check_SetnDel(t, tester) check := <-tester if !check { t.Error("SetnDelete Failed, please check implementation") } else { fmt.Println("Testcase - TestSetnDelete : Passed") } } func check_SetnDel(t *testing.T, tester chan bool) { LeaderAdd := "127.0.0.1:900" + get_LeaderId("1") conn, error := net.Dial("tcp", LeaderAdd) if error != nil { tester <- false conn.Close() } reader := bufio.NewReader(conn) //------------Delete Check---------------------- io.Copy(conn, bytes.NewBufferString("set Roll104 50 9\r\nTarunjain\r\n")) res, err := reader.ReadString('\n') io.Copy(conn, bytes.NewBufferString("delete Roll104\r\n")) res, err = reader.ReadString('\n') if err != nil { tester <- false conn.Close() } else { if string(res) == "DELETED\r\n" { tester <- true conn.Close() } else { tester <- false conn.Close() } } conn.Close() } /* //..............................................................................................................................// // Testcase: To test whether multiple clients works together properly. //..............................................................................................................................// func TestMulticlient(t *testing.T) { tester := make(chan int) Serv := returnRandServ() LeaderIdReturned := get_LeaderId(strconv.Itoa(Serv)) for i := 0; i < noOfThreads; i++ { go multiclient(t, tester, LeaderIdReturned) } count := 0 for i := 0; i < noOfThreads; i++ { count += <-tester } if count != noOfThreads { t.Error("TestMulticlient Failed") } else { fmt.Println("Testcase - TestMulticlient : Passed") } } func multiclient(t *testing.T, tester chan int, LeaderIdReturned string) { //Serv := returnRandServ() //LeaderIdReturned := get_LeaderId(strconv.Itoa(Serv)) LeaderAdd := "127.0.0.1:900" + LeaderIdReturned conn, error := net.Dial("tcp", LeaderAdd) if error != nil { conn.Close() } reader := bufio.NewReader(conn) io.Copy(conn, bytes.NewBufferString("set key71 500 2\r\ntj\r\n")) res, err := reader.ReadBytes('\n') if err != nil { conn.Close() } else { if strings.Contains(strings.TrimSpace(string(res)), "OK") { tester <- 1 } else { tester <- 0 } } conn.Close() } */ //..............................................................................................................................// // Testcase to test Basic Set and Get (checking log replication, using server killing) //..............................................................................................................................// func TestSetnGetKill(t *testing.T) { tester := make(chan bool) go check_SetnGetKill(t, tester) check := <-tester if !check { t.Error("SetnGetKill Failed, please check implementation") } else { fmt.Println("Testcase - TestSetnGetKill : Passed") } } func check_SetnGetKill(t *testing.T, tester chan bool) { Serv := returnRandServ() LeaderIdReturned := get_LeaderId(strconv.Itoa(Serv)) //fmt.Println("hi ",LeaderIdReturned) LeaderId, _ := strconv.Atoi(LeaderIdReturned) LeaderAdd := "127.0.0.1:900" + LeaderIdReturned conn, error := net.Dial("tcp", LeaderAdd) if error != nil { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("set key51 50 5\r\nTarun\r\n")) reader := bufio.NewReader(conn) resp, error := reader.ReadBytes('\n') if error != nil { conn.Close() } else { if len(string(resp)) > 0 { response := strings.Split(strings.TrimSpace(string(resp)), " ") if response[0] != "OK" { tester <- false conn.Close() } } else { tester <- false conn.Close() } } killServer(LeaderId) Serv1 := returnRandServ() //fmt.Println(servermap) //fmt.Println(Serv1) LeaderIdReturned1 := get_LeaderId(strconv.Itoa(Serv1)) //fmt.Println(LeaderIdReturned1) LeaderId1, _ := strconv.Atoi(LeaderIdReturned1) //fmt.Println(LeaderId1) killServer(LeaderId1) //time.Sleep(time.Second * 1) Serv2 := returnRandServ() //fmt.Println(servermap) //fmt.Println(Serv2) LeaderIdReturned2 := get_LeaderId(strconv.Itoa(Serv2)) //fmt.Println(LeaderIdReturned2) //LeaderId2,_ := strconv.Atoi(LeaderIdReturned2) LeaderAdd = "127.0.0.1:900" + LeaderIdReturned2 conn1, error := net.Dial("tcp", LeaderAdd) if error != nil { tester <- false conn1.Close() } io.Copy(conn1, bytes.NewBufferString("get key51\r\n")) reader = bufio.NewReader(conn1) resp, error = reader.ReadBytes('\n') if error != nil { conn1.Close() } else { response := strings.Split(strings.TrimSpace(string(resp)), " ") if response[0] == "VALUE" || response[1] == "5" { res, error := reader.ReadString('\n') if error != nil { conn1.Close() } else { if res == "Tarun\r\n" { tester <- true conn1.Close() } else { tester <- false conn1.Close() } } } else { tester <- false conn1.Close() } } //wgroup.Add(1) go execute_cmd(LeaderId) //restarting the killed servers //wgroup.Add(1) go execute_cmd(LeaderId1) //restarting the killed servers //time.Sleep(time.Second * 2) //tester <- true //wgroup.Wait() conn1.Close() } /* //..............................................................................................................................// // Testcase to test Leader Election - 2 (Killing the Fisrt Leader And another random Server) //..............................................................................................................................// func TestLeaderElect2(t *testing.T) { tester := make(chan bool) time.Sleep(time.Second * 6) go check_LeaderElect2(t, tester) check := <-tester if !check { t.Error("TestLeaderElect2 Failed, please check implementation") } else { fmt.Println("Testcase - TestLeaderElect2 : Passed") } } func check_LeaderElect2(t *testing.T, tester chan bool) { Serv := returnRandServ() //fmt.Println("hi = ",Serv) LeaderIdReturned := get_LeaderId(strconv.Itoa(Serv)) //fmt.Println("hi = ",LeaderIdReturned) LeaderId, _ := strconv.Atoi(LeaderIdReturned) killServer(LeaderId) Serv1 := returnRandServ() killServer(Serv1) //fmt.Println(Serv1) Serv2 := returnRandServ() //time.Sleep(time.Second * 2) //fmt.Println(Serv2) LeaderIdReturned = get_LeaderId(strconv.Itoa(Serv2)) LeaderAdd := "127.0.0.1:900" + LeaderIdReturned //fmt.Println(LeaderAdd) conn, error := net.Dial("tcp", LeaderAdd) if error != nil { tester <- false conn.Close() } io.Copy(conn, bytes.NewBufferString("get LeaderTester\r\n")) reader := bufio.NewReader(conn) resp, error := reader.ReadBytes('\n') if error != nil { conn.Close() } else { response := strings.Split(strings.TrimSpace(string(resp)), " ") if response[0] == "ERRNOTFOUND" { tester <- true conn.Close() } else { tester <- false conn.Close() } } //wgroup.Add(1) go execute_cmd(LeaderId) //wgroup.Add(1) go execute_cmd(Serv1) //tester<-true } */ func TestKillAllServers(t *testing.T) { cmd := exec.Command("pkill", "kvstore") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { t.Log(err) } cmd.Wait() } func restartServerAfterSomeTime(LeaderId2 int) { time.Sleep(time.Second * 6) go execute_cmd(LeaderId2) fmt.Println("Restarting ", LeaderId2) }
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package operationparser import ( "encoding/json" "fmt" "github.com/pkg/errors" "github.com/trustbloc/sidetree-core-go/pkg/api/operation" "github.com/trustbloc/sidetree-core-go/pkg/docutil" internal "github.com/trustbloc/sidetree-core-go/pkg/internal/jws" "github.com/trustbloc/sidetree-core-go/pkg/jws" "github.com/trustbloc/sidetree-core-go/pkg/versions/0_1/model" ) // ParseRecoverOperation will parse recover operation. func (p *Parser) ParseRecoverOperation(request []byte, anchor bool) (*model.Operation, error) { schema, err := p.parseRecoverRequest(request) if err != nil { return nil, err } _, err = p.ParseSignedDataForRecover(schema.SignedData) if err != nil { return nil, err } if !anchor { err = p.ValidateDelta(schema.Delta) if err != nil { return nil, err } } return &model.Operation{ OperationBuffer: request, Type: operation.TypeRecover, UniqueSuffix: schema.DidSuffix, Delta: schema.Delta, SignedData: schema.SignedData, }, nil } func (p *Parser) parseRecoverRequest(payload []byte) (*model.RecoverRequest, error) { schema := &model.RecoverRequest{} err := json.Unmarshal(payload, schema) if err != nil { return nil, fmt.Errorf("failed to unmarshal recover request: %s", err.Error()) } if err := p.validateRecoverRequest(schema); err != nil { return nil, err } return schema, nil } // ParseSignedDataForRecover will parse and validate signed data for recover. func (p *Parser) ParseSignedDataForRecover(compactJWS string) (*model.RecoverSignedDataModel, error) { jws, err := p.parseSignedData(compactJWS) if err != nil { return nil, fmt.Errorf("recover: %s", err.Error()) } schema := &model.RecoverSignedDataModel{} err = json.Unmarshal(jws.Payload, schema) if err != nil { return nil, fmt.Errorf("failed to unmarshal signed data model for recover: %s", err.Error()) } if err := p.validateSignedDataForRecovery(schema); err != nil { return nil, err } return schema, nil } func (p *Parser) validateSignedDataForRecovery(signedData *model.RecoverSignedDataModel) error { if err := p.validateSigningKey(signedData.RecoveryKey, p.KeyAlgorithms); err != nil { return fmt.Errorf("signed data for recovery: %s", err.Error()) } code := uint64(p.MultihashAlgorithm) if !docutil.IsComputedUsingHashAlgorithm(signedData.RecoveryCommitment, code) { return fmt.Errorf("next recovery commitment hash is not computed with the required hash algorithm: %d", code) } if !docutil.IsComputedUsingHashAlgorithm(signedData.DeltaHash, code) { return fmt.Errorf("patch data hash is not computed with the required hash algorithm: %d", code) } return nil } func (p *Parser) parseSignedData(compactJWS string) (*internal.JSONWebSignature, error) { if compactJWS == "" { return nil, errors.New("missing signed data") } jws, err := internal.ParseJWS(compactJWS) if err != nil { return nil, fmt.Errorf("failed to parse signed data: %s", err.Error()) } err = p.validateProtectedHeaders(jws.ProtectedHeaders, p.SignatureAlgorithms) if err != nil { return nil, fmt.Errorf("failed to parse signed data: %s", err.Error()) } return jws, nil } func (p *Parser) validateProtectedHeaders(headers jws.Headers, allowedAlgorithms []string) error { if headers == nil { return errors.New("missing protected headers") } // kid MUST be present in the protected header. // alg MUST be present in the protected header, its value MUST NOT be none. // no additional members may be present in the protected header. // TODO: There is discrepancy between spec "kid MUST be present in the protected header" (issue-365) // and reference implementation ('kid' is not present; only one 'alg' header expected) // so disable this check for now // _, ok := headers.KeyID() // if !ok { // return errors.New("kid must be present in the protected header") // } alg, ok := headers.Algorithm() if !ok { return errors.New("algorithm must be present in the protected header") } if alg == "" { return errors.New("algorithm cannot be empty in the protected header") } allowedHeaders := map[string]bool{ jws.HeaderAlgorithm: true, jws.HeaderKeyID: true, } for k := range headers { if _, ok := allowedHeaders[k]; !ok { return fmt.Errorf("invalid protected header: %s", k) } } if !contains(allowedAlgorithms, alg) { return errors.Errorf("algorithm '%s' is not in the allowed list %v", alg, allowedAlgorithms) } return nil } func (p *Parser) validateRecoverRequest(recover *model.RecoverRequest) error { if recover.DidSuffix == "" { return errors.New("missing did suffix") } if recover.SignedData == "" { return errors.New("missing signed data") } return nil } func (p *Parser) validateSigningKey(key *jws.JWK, allowedAlgorithms []string) error { if key == nil { return errors.New("missing signing key") } err := key.Validate() if err != nil { return fmt.Errorf("signing key validation failed: %s", err.Error()) } if !contains(allowedAlgorithms, key.Crv) { return errors.Errorf("key algorithm '%s' is not in the allowed list %v", key.Crv, allowedAlgorithms) } return nil } func contains(values []string, value string) bool { for _, v := range values { if v == value { return true } } return false }
/* Package storagecache provides a mechanism for using various storage as datastore's cache. This package will not be used directly, but it will be used via aememcache or redicache. This package automatically processes so that the cache state matches the Entity on Datastore. The main problem is transactions. Do not read from cache under transaction. Under a transaction it should not be added to the cache until it is committed or rolled back. In order to avoid troublesome bugs, under the transaction, Get, Put and Delete only record the Key, delete all caches related to the Key recorded when committed. For now, no caching is made for the Entity that returned from the query. If you want to cache it, there is a way to query with KeysOnly first, and exec GetMulti next. In all operations, the key target is determined by KeyFilter. In order to make consistency easy, we recommend using the same settings throughout the application. */ package storagecache // import "go.mercari.io/datastore/dsmiddleware/storagecache"
package modules import ( "fmt" "net/http" "net/url" "strings" "github.com/sirupsen/logrus" ) // NotificationController operations for Notification type NotificationController struct { BaseUserController } // PostMessage ... // @Title PostMessage // @Description create Notification // @Success 204 // @Failure 403 body is empty // @router /post [post] func (c *NotificationController) PostMessage() { if err := SendActiveNotifications(); err != nil { c.ErrorAbort(500, err) } c.Success(http.StatusNoContent, nil) } // PostMenualMessage ... // @Title PostMenualMessage // @Description create Notification // @Success 204 // @Failure 403 body is empty // @router /post/:key [post] func (c *NotificationController) PostMenualMessage() { key := c.Ctx.Input.Param(":key") if key == "" { c.ErrorAbort(400, nil) } //TODO: key에 대한 처리 group := c.Ctx.Input.Query("group") notificationTypes, err := GetNotificationsTypes(true) if err != nil { c.ErrorAbort(500, err) } for _, notificationType := range notificationTypes { if notificationType.Group != group { continue } listValueGroup := []KeyValue{} if notificationType.ResourceName != "" { var err error rows, err := GetRows(notificationType.ResourceName, notificationType.TargetWhere) if err != nil { logrus.WithError(err).Error() continue } for _, row := range rows { listValues := KeyValue{} for key, value := range row { listValues[fmt.Sprintf("list_%s", key)] = convInterface(value) } listValueGroup = append(listValueGroup, listValues) } } notification := MakeNotification(&notificationType, nil, listValueGroup) if err := addNotificationAndSendNotification(notification); err != nil { logrus.WithError(err).Error() continue } } c.Success(http.StatusNoContent, nil) } func SendActiveNotifications() error { crudEvents, err := GetCrudEventaByCheckedNotification(false) if err != nil { return err } notificationTypes, err := GetNotificationsTypes(false) if err != nil { return err } mapCheckedCrudEvent := []uint{} for _, crudEvent := range crudEvents { if err := sendActiveNotificationsEachCrudEvent(&crudEvent, notificationTypes); err == nil { mapCheckedCrudEvent = append(mapCheckedCrudEvent, crudEvent.ID) } } if err := UpdateCheckedNotificationByCrudEventIDs(mapCheckedCrudEvent, true); err != nil { logrus.WithError(err).Error() } return nil } func sendActiveNotificationsEachCrudEvent(crudEvent *CrudEvent, notificationTypes []NotificationType) error { for _, notificationType := range notificationTypes { if notificationType.ResourceName != "" && crudEvent.ResourceName != notificationType.ResourceName { continue } if notificationType.ActionName != "" && crudEvent.ActionName != notificationType.ActionName { continue } if notificationType.ActionType != "" && crudEvent.ActionType != notificationType.ActionType { continue } if notificationType.DiffMode { if !notificationType.CheckDiff(crudEvent) { continue } } templateKeyValueMaker := NewTemplateKeyValueMaker(crudEvent, &notificationType) getDBValueParams := templateKeyValueMaker.MakeGetValueParams() templateKeyValueMaker.LoadValues(getDBValueParams) notification := MakeNotification(&notificationType, templateKeyValueMaker.GetedValues, nil) notification.EventUserID = crudEvent.CreatorID if err := addNotificationAndSendNotification(notification); err != nil { logrus.WithError(err).Error() } } return nil } func addNotificationAndSendNotification(notification *Notification) error { //TODO: Warning! 전송 후 DB에러 시 다시 노티 전송 될 수 있음 if notification.NotificationType.WebhookURLs == "" { return nil } for _, targetURL := range strings.Split(notification.NotificationType.WebhookURLs, "\n") { webhookURL, err := url.Parse(strings.TrimSpace(targetURL)) if err != nil { logrus.WithError(err).Error("") continue } parameters := webhookURL.Query() parameters.Add("title", notification.Title) parameters.Add("message", notification.Message) webhookURL.RawQuery = parameters.Encode() if _, err := req("GET", webhookURL.String(), nil, nil, nil); err != nil { logrus.WithError(err).Error() } } if _, err := AddNotification(notification); err != nil { return err } return nil }
package logger import ( "go.uber.org/zap" "testing" ) func TestLogger(t *testing.T) { cfg := new(LogConfig) cfg.Develop = true cfg.Level = "debug" cfg.Path = "./test.log" cfg.ErrorPath = "./test-error.log" log := NewRotateLogger(*cfg) defer log.Sync() log.Debug("debug", zap.String("aaa", "bbb"), zap.String("ccc", "ddd")) log.Info("info") log.Warn("warn") log.Error("error") log1 := log.Sugar() log1.Debugf("debug: %s", "aaa") log1.Infof("info: %s", "bbb") log1.Warnf("warn: %s", "ccc") log1.Errorf("error: %s", "ddd") }
package user import ( "fmt" "github.com/btnguyen2k/prom" "main/src/gvabe/bo" "github.com/btnguyen2k/henge" ) // NewUserDaoSql is helper method to create SQL-implementation of UserDao. func NewUserDaoSql(sqlc *prom.SqlConnect, tableName string) UserDao { dao := &UserDaoSql{} dao.UniversalDao = henge.NewUniversalDaoSql(sqlc, tableName, true, nil) return dao } // InitUserTableSql is helper function to initialize SQL-based table to store users. // This function also creates table indexes if needed. // // Available since v0.7.0. func InitUserTableSql(sqlc *prom.SqlConnect, tableName string) error { switch sqlc.GetDbFlavor() { case prom.FlavorPgSql: return henge.InitPgsqlTable(sqlc, tableName, nil) case prom.FlavorMsSql: return henge.InitMssqlTable(sqlc, tableName, nil) case prom.FlavorMySql: return henge.InitMysqlTable(sqlc, tableName, nil) case prom.FlavorOracle: return henge.InitOracleTable(sqlc, tableName, nil) case prom.FlavorSqlite: return henge.InitSqliteTable(sqlc, tableName, nil) case prom.FlavorCosmosDb: return henge.InitCosmosdbCollection(sqlc, tableName, &henge.CosmosdbCollectionSpec{Pk: bo.CosmosdbPkName}) } return fmt.Errorf("unsupported database type %v", sqlc.GetDbFlavor()) } // UserDaoSql is SQL-implementation of UserDao. type UserDaoSql struct { henge.UniversalDao } // Delete implements UserDao.Delete. func (dao *UserDaoSql) Delete(bo *User) (bool, error) { return dao.UniversalDao.Delete(bo.UniversalBo) } // Create implements UserDao.Create. func (dao *UserDaoSql) Create(bo *User) (bool, error) { return dao.UniversalDao.Create(bo.sync().UniversalBo) } // Get implements UserDao.Get. func (dao *UserDaoSql) Get(id string) (*User, error) { ubo, err := dao.UniversalDao.Get(id) return NewUserFromUbo(ubo), err } // Update implements UserDao.Update. func (dao *UserDaoSql) Update(bo *User) (bool, error) { return dao.UniversalDao.Update(bo.sync().UniversalBo) }
package main func main() { addFunc := func(terms ...int) (numTerms int, sum int) { for _, term := range terms { sum += term } numTerms = len(terms) return } x, y := addFunc(1, 2, 3, 4, 5 ,6) println(x, y) }
//go:build go1.15 // +build go1.15 package time import ( "sync" "time" ) var tickerPool = sync.Pool{} // AcquireTicker returns a ticker from the pool if possible. func AcquireTicker(d time.Duration) *time.Ticker { v := tickerPool.Get() if v == nil { return time.NewTicker(d) } t, ok := v.(*time.Ticker) if !ok { panic("unexpected type of time.Ticker") } t.Reset(d) return t } // ReleaseTicker returns a ticker into the pool. func ReleaseTicker(tm *time.Ticker) { tm.Stop() tickerPool.Put(tm) }
package utils import ( "fmt" "os" "time" log "github.com/sirupsen/logrus" ) // configure logging using env variables func ConfigureLogging() { InitLogging(log.DebugLevel) strlevel := Getenv("LOG_LEVEL", "TRACE") level := parseLogLevel(strlevel) log.SetLevel(level) style := os.Getenv("LOG_STYLE") if style == "json" { initJSONLogStyle() } } // implement Log function to enable additional log fields // usage: utils.Log("my_field_1", 1, "my_field_2", 4.3).Info("Testing logging") func Log(args ...interface{}) *log.Entry { nArgs := len(args) fields := log.Fields{} if nArgs % 2 != 0 { log.Warningf("Unable to accept odd (%d) arguments count in utils.DebugLog method.", nArgs) } else { for i := 0; i < nArgs; i+=2 { fields[args[i].(string)] = args[i+1] } } return log.WithFields(fields) } // parse log.Level from string or fail func parseLogLevel(strlevel string) log.Level { level, err := log.ParseLevel(strlevel) if err != nil { panic(fmt.Errorf("Unable to parse log level: %v", err)) } return level } // configure logging to stdout with given loglevel func InitLogging(level log.Level) { log.SetOutput(os.Stdout) log.SetLevel(level) } // configure json logging format for Logstash func initJSONLogStyle(){ log.SetFormatter(&log.JSONFormatter{ TimestampFormat: time.RFC3339, FieldMap: log.FieldMap{ log.FieldKeyTime: "@timestamp", log.FieldKeyLevel: "levelname", log.FieldKeyMsg: "message", }, }) }
package main import ( "fmt" "os" "io" "io/ioutil" "path" "strings" "log" "crypto/md5" "encoding/hex" ) func main() { filepath := "E:\\" files, err := ioutil.ReadDir(filepath) if err != nil { log.Fatal(err) } for _, f := range files { fmt.Println(f.Name()) if f.IsDir() { fmt.Println(f.Name(), " is dir") continue } name := f.Name() ext := path.Ext(name) file, err := os.Open(filepath + f.Name()) if err != nil { fmt.Println(f.Name(), "open error") continue } md5 := md5.New() io.Copy(md5, file) file.Close() md5str := hex.EncodeToString(md5.Sum(nil)) fmt.Println(filepath + md5str + ext) err = os.Rename(filepath + f.Name(), filepath + md5str + "." + ext) if err != nil { fmt.Println(f.Name(), err.Error()) continue } } filepath = "E:\\" list := "" files2 := strings.Split(list, " | ") for _, name := range files2 { filename := filepath +"\\" + name log.Println("-----", filename) err := os.Remove(filename) if err != nil { log.Println(err.Error()) } } }
package vcs import ( "net/http" "os" "sync" "github.com/sirkon/goproxy/internal/errors" "github.com/sirkon/goproxy" "github.com/sirkon/goproxy/internal/modfetch" ) // plugin creates source for VCS repositories type plugin struct { rootDir string // accessLock is for access to inWork accessLock sync.Locker inWork map[string]modfetch.Repo } func (f *plugin) String() string { return "legacy" } // NewPlugin creates new valid plugin instance func NewPlugin(rootDir string) (f goproxy.Plugin, err error) { setupEnv(rootDir) stat, err := os.Stat(rootDir) if os.IsNotExist(err) { if err := os.MkdirAll(rootDir, 0755); err != nil { return nil, errors.Wrapf(err, "vcs creating directory `%s`", rootDir) } } else { if !stat.IsDir() { return nil, errors.Newf("vcs %s is not a directory", rootDir) } } if err = os.Chdir(rootDir); err != nil { return nil, errors.Wrapf(err, "vcs cding into `%s`", rootDir) } if err = os.Setenv("GOPATH", rootDir); err != nil { return nil, errors.Wrapf(err, "vcs setting up GOPATH environment variable") } if err = os.Setenv("GO111MODULE", "on"); err != nil { return nil, errors.Wrapf(err, "vcs setting up GO111MODULE environment variable") } return &plugin{ rootDir: rootDir, inWork: map[string]modfetch.Repo{}, accessLock: &sync.Mutex{}, }, nil } // Module creates a source for a module with given path func (f *plugin) Module(req *http.Request, prefix string) (goproxy.Module, error) { path, _, err := goproxy.GetModInfo(req, prefix) if err != nil { return nil, err } repo, err := f.getRepo(path) if err != nil { return nil, err } return &vcsModule{ repo: repo, }, nil } // Leave unset a lock of a given module func (f *plugin) Leave(s goproxy.Module) error { return nil } // Close ... func (f *plugin) Close() error { return nil } func (f *plugin) getRepo(path string) (repo modfetch.Repo, err error) { f.accessLock.Lock() defer f.accessLock.Unlock() repo, ok := f.inWork[path] if !ok { repo, err = modfetch.Lookup(path) if err != nil { return nil, errors.Wrapf(err, "vcs getting module for `%s`", path) } } f.inWork[path] = repo return repo, nil }
package elemental import ( "context" "errors" "fmt" "time" "github.com/Nv7-Github/Nv7Haven/pb" "google.golang.org/protobuf/types/known/emptypb" ) func (e *Elemental) CreateSugg(_ context.Context, req *pb.CreateRequest) (*emptypb.Empty, error) { suc, msg := e.CreateSuggestion(req.Mark, req.Pioneer, req.Elem1, req.Elem2, req.Id) if !suc { return &emptypb.Empty{}, errors.New(msg) } return &emptypb.Empty{}, nil } func (e *Elemental) incrementUses(id string) error { elem, err := e.GetElement(id) if err != nil { return err } elem.Uses++ lock.Lock() e.cache[elem.Name] = elem lock.Unlock() _, err = e.db.Exec("UPDATE elements SET uses=? WHERE name=?", elem.Uses, elem.Name) if err != nil { return err } return nil } // CreateSuggestion creates a suggestion func (e *Elemental) CreateSuggestion(mark string, pioneer string, elem1 string, elem2 string, id string) (bool, string) { existing, err := e.getSugg(id) if err != nil { return false, err.Error() } if !(existing.Votes >= maxVotes) && (time.Now().Weekday() != anarchyDay) { return false, "This element still needs more votes!" } // Get combos combos, err := e.GetSuggestions(elem1, elem2) if err != nil { return false, err.Error() } // Delete hanging elements for _, val := range combos { _, err = e.db.Exec("DELETE FROM suggestions WHERE name=?", val) if err != nil { return false, err.Error() } } // Delete combos _, err = e.db.Exec("DELETE FROM sugg_combos WHERE (elem1=? AND elem2=?) OR (elem1=? AND elem2=?)", elem1, elem2, elem2, elem1) if err != nil { return false, err.Error() } res, err := e.db.Query("SELECT COUNT(1) FROM elements WHERE name=?", existing.Name) if err != nil { return false, err.Error() } defer res.Close() parent1, err := e.GetElement(elem1) if err != nil { return false, err.Error() } parent2, err := e.GetElement(elem2) if err != nil { return false, err.Error() } complexity := max(parent1.Complexity, parent2.Complexity) + 1 err = e.incrementUses(elem1) if err != nil { return false, err.Error() } if elem2 != elem1 { err = e.incrementUses(elem2) if err != nil { return false, err.Error() } } var count int res.Next() res.Scan(&count) if count == 0 { color := fmt.Sprintf("%s_%f_%f", existing.Color.Base, existing.Color.Saturation, existing.Color.Lightness) _, err = e.db.Exec("INSERT INTO elements VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )", existing.Name, color, mark, elem1, elem2, existing.Creator, pioneer, int(time.Now().Unix())*1000, complexity, 0, 0) if err != nil { return false, err.Error() } } // Create combo err = e.addCombo(elem1, elem2, existing.Name) if err != nil { return false, err.Error() } // New Recent Combo err = e.NewRecent(&pb.RecentCombination{ Elem1: elem1, Elem2: elem2, Elem3: id, }) if err != nil { return false, err.Error() } return true, "" }
package byopenwrt import ( "bylib/byhttp" "bylib/bylog" "bylib/byutils" "fmt" "github.com/go-cmd/cmd" "github.com/pkg/errors" "os" "os/signal" "strings" "syscall" ) type SysAdmin struct{ UploadFlag bool } //获取系统时间 func (s *SysAdmin)getSysTime(ctx *byhttp.MuxerContext)error { dt:=byutil.OpDateTime{ } if err:=GetSysDateTime(&dt);err!=nil{ bylog.Error("GetSysDateTime err=%v",err) return ctx.Json(400,err) } return ctx.Json(200,dt) } //设置系统时间 func (s *SysAdmin)setSysTime(ctx *byhttp.MuxerContext)error { dt:=byutil.OpDateTime{ } if err:=ctx.BindJson(&dt);err!=nil{ bylog.Error("setSysTime BindJson err=%v",err) return ctx.Json(400,err) } if err:=SetSysDateTime(dt);err!=nil{ bylog.Error("SetSysDateTime error=%v",err) return ctx.Json(400,err) } return ctx.Json(200,"ok") } //上传文件 func (s *SysAdmin)doUpload(dst string)error{ //执行命令 //sysupgrade -n -v xx.bin s.UploadFlag = true aps:=cmd.NewCmd("touch","/tmp/failsafe") status := <-aps.Start() if status.Error!=nil{ bylog.Error("sysupgrade err=%v",status.Error) } aps=cmd.NewCmd("/sbin/sysupgrade","-n","-v",dst) //等待aps完成 status = <-aps.Start() if status.Error!=nil{ bylog.Error("sysupgrade err=%v",status.Error) return status.Error } msg:=strings.Join(status.Stdout,"") if strings.Contains(msg,"Invalid image type"){ return errors.New("错误的文件格式") } return status.Error } func (s *SysAdmin)SysUpdate(ctx *byhttp.MuxerContext)error{ file, err := ctx.FormFile("file") if err!=nil{ bylog.Error("FromFile err %v",err) return ctx.Json(400,err) } bylog.Debug("upload file name=%s",file.Filename) dst:="/tmp/"+file.Filename err=ctx.SaveUploadedFile(file,dst) if err!=nil{ bylog.Error("SaveUploadedFile %s err %v",dst,err) return ctx.Json(400,err) } if err:=s.doUpload(dst);err!=nil{ return ctx.Json(400,err) } return ctx.Json(200,"ok") } func (s *SysAdmin)HookSignal(){ c := make(chan os.Signal) //监听指定信号 ctrl+c kill signal.Notify(c, syscall.SIGTERM, syscall.SIGKILL,syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT) go func() { for sig := range c { switch sig { case syscall.SIGTERM, syscall.SIGKILL,syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT: bylog.Debug("Receive SIGTERM,SIGKILL,SIGHUP") if s.UploadFlag{ bylog.Debug("Ignore for upload") }else{ //Debug("Kill me") //os.Exit(0) } default: fmt.Println("other", s) } } }() } func (self *SysAdmin)ResetDevice(ctx *byhttp.MuxerContext)error{ aps:=cmd.NewCmd("reboot","") //等待aps完成 status := <-aps.Start() if status.Error!=nil{ ctx.Json(400,status.Error) } return ctx.Json(200,"OK") } func (s *SysAdmin)Start()error{ //s.HookSignal() byhttp.GetMuxServer().Post("/upload",s.SysUpdate) byhttp.GetMuxServer().Get("/device/reset",s.ResetDevice) byhttp.GetMuxServer().Get("/time",s.getSysTime) byhttp.GetMuxServer().Post("/time",s.setSysTime) return nil } func SysAdminGet()*SysAdmin{ return &SysAdmin{ UploadFlag:false, } }
package entities // User defines a user in the program. type User struct { Name string email string }
package slackbot import ( "context" "log" "time" ) const maxErrors = 3 const tickDuration = 20 * time.Second // 1m20s const monitorErrorMarginDuration = (maxErrors + 1) * tickDuration // Monitor polls Cloud Build until the build reaches completed status, then triggers the Slack event. func Monitor(ctx context.Context, projectId string, buildId string, webhook string, project string) { svc := gcbClient(ctx) errors := 0 started := false t := time.Tick(tickDuration) for { log.Printf("Polling build %s", buildId) getMonitoredBuild := svc.Projects.Builds.Get(projectId, buildId) monitoredBuild, err := getMonitoredBuild.Do() if err != nil { if errors <= maxErrors { log.Printf("Failed to get build details from Cloud Build. Will retry in %s", tickDuration) errors++ continue } else { log.Fatalf("Reached maximum number of errors (%d). Exiting", maxErrors) } } switch monitoredBuild.Status { case "WORKING": if !started { log.Printf("Build started. Notifying") Notify(monitoredBuild, webhook, project) started = true } case "SUCCESS", "FAILURE", "INTERNAL_ERROR", "TIMEOUT", "CANCELLED": log.Printf("Terminal status reached. Notifying") Notify(monitoredBuild, webhook, project) return } <-t } }
package main import "fmt" func main() { ch :=GenerateNatural() // 自然数序列 2,3,4 for i:=0;i<100;i++ { prime :=<-ch // 新出现的素数 fmt.Printf("%v: %v\n",i+1,prime) ch =PrimeFilter(ch,prime) // 基于新素数构造的过滤器 } } //返回生成自然数序列的channel 2,3,4,5,... func GenerateNatural() chan int { ch :=make(chan int) go func() { for i :=2;;i++{ ch<-i } }() return ch } // 通道过滤器: 删除能被素数整除的数 func PrimeFilter(in <-chan int, prime int) chan int{ out :=make(chan int) go func() { for { if i :=<-in;i%prime!=0{ out<-i } } }() return out }
package main import ( "encoding/json" "fmt" "github.com/ethereum/go-ethereum/common" "github.com/hyperorchidlab/go-miner-pool/account" com "github.com/hyperorchidlab/go-miner-pool/common" "github.com/hyperorchidlab/go-miner/node" "github.com/spf13/cobra" "io/ioutil" "os" "path/filepath" ) var InitCmd = &cobra.Command{ Use: "init", Short: "init miner node", Long: `TODO::.`, Run: initMiner, } func init() { InitCmd.Flags().StringVarP(&param.password, "password", "p", "", "Password to create Hyper Orchid block chain system.") } func initMiner(_ *cobra.Command, _ []string) { baseDir := node.BaseDir() if _, ok := com.FileExists(baseDir); ok { fmt.Println("Duplicate init operation") return } if len(param.password) == 0 { pwd, err := com.ReadPassWord2() if err != nil { panic(err) } param.password = pwd } if err := os.Mkdir(baseDir, os.ModePerm); err != nil { panic(err) } w, err := account.NewWallet(param.password) if err != nil { panic(err) } if err := w.SaveToPath(node.WalletDir(baseDir)); err != nil { panic(err) } fmt.Println("Create wallet success!") defaultSys := &node.Conf{ EthereumConfig: &com.EthereumConfig{ NetworkID: com.RopstenNetworkId, EthApiUrl: "https://ropsten.infura.io/v3/fe5ffffba0bf46bb9dc27fd5e04cd6cb", MicroPaySys: common.HexToAddress("0xbabababababababababababababababababababa"), Token: common.HexToAddress("0xbabababababababababababababababababababa"), }, BAS: "108.61.223.99", } byt, err := json.MarshalIndent(defaultSys, "", "\t") confPath := filepath.Join(baseDir, string(filepath.Separator), node.ConfFile) if err := ioutil.WriteFile(confPath, byt, 0644); err != nil { panic(err) } }
/* The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. To generate the nth term, just count and say the n-1th term. */ package main import "fmt" func main() { for i := 1; i <= 10; i++ { fmt.Println(i, countandsay(i)) } } // https://oeis.org/A005150 func countandsay(n int) string { if n <= 0 { return "" } s := "1" for i := 1; i < n; i++ { s += "$" t := "" c := 1 for j := 1; j < len(s); j++ { if s[j] != s[j-1] { t += fmt.Sprintf("%d%c", c, s[j-1]) c = 1 } else { c++ } } s = t } return s }
package main import ( "fmt" "encoding/json" "github.com/hyperledger/fabric/core/chaincode/shim" "github.com/hyperledger/fabric/protos/peer" ) // ============================================================ // initVote - create a new vote and store into chaincode state // ============================================================ func (vc *VoteChaincode) initVote(stub shim.ChaincodeStubInterface, args []string) peer.Response { type voteTransientInput struct { PollID string `json:"pollID"` VoterID string `json:"voterID"` VoterSex string `json:"voterSex"` VoterAge int `json:"voterAge"` Salt string `json:"salt"` VoteHash string `json:"voteHash"` } fmt.Println("- start init vote") if len(args) != 0 { return shim.Error("Private data should be passed in transient map.") } transMap, err := stub.GetTransient() if err != nil { return shim.Error("Error getting transient: " + err.Error()) } voteJsonBytes, success := transMap["vote"] if !success { return shim.Error("vote must be a key in the transient map") } if len(voteJsonBytes) == 0 { return shim.Error("vote value in transient map cannot be empty JSON string") } var voteInput voteTransientInput err = json.Unmarshal(voteJsonBytes, &voteInput) if err != nil { return shim.Error("failed to decode JSON of: " + string(voteJsonBytes)) } // input sanitation if len(voteInput.PollID) == 0 { return shim.Error("poll ID field must be a non-empty string") } if len(voteInput.VoterID) == 0 { return shim.Error("voter ID field must be a non-empty string") } if voteInput.VoterAge <= 0 { return shim.Error("age field must be > 0") } if len(voteInput.VoterSex) == 0 { return shim.Error("sex field must be a non-empty string") } if len(voteInput.Salt) == 0 { return shim.Error("salt must be > 0") } if len(voteInput.VoteHash) == 0 { return shim.Error("vote hash field must be a non-empty string") } var p poll existingPollAsBytes, err := stub.GetPrivateData("collectionPoll", voteInput.PollID) if err != nil { return shim.Error("Failed to get associated poll: " + err.Error()) } else if existingPollAsBytes == nil { return shim.Error("Poll does not exist: " + voteInput.PollID) } err = json.Unmarshal(existingPollAsBytes, &p) if err != nil { return shim.Error(err.Error()) } // Increment num votes of poll p.NumVotes++ pollJSONasBytes, err := json.Marshal(p) if err != nil { return shim.Error(err.Error()) } err = stub.PutPrivateData("collectionPoll", voteInput.PollID, pollJSONasBytes) if err != nil { return shim.Error(err.Error()) } // create a composite key for vote collection using the poll ID and voter ID attrVoteCompositeKey := []string{voteInput.PollID, voteInput.VoterID} voteCompositeKey, err := stub.CreateCompositeKey("vote", attrVoteCompositeKey) if err != nil { return shim.Error("Failed to create composite key for vote: " + err.Error()) } // check if value for voteCompositeKey already exists existingVoteAsBytes, err := stub.GetPrivateData("collectionVote", voteCompositeKey) if err != nil { return shim.Error("Failed to get vote: " + err.Error()) } else if existingVoteAsBytes != nil { fmt.Println("This vote already exists: " + voteInput.PollID + voteInput.VoterID) return shim.Error("This vote already exists: " + voteInput.PollID + voteInput.VoterID) } vote := &vote{ ObjectType: "vote", PollID: voteInput.PollID, VoterID: voteInput.VoterID, VoterAge: voteInput.VoterAge, VoterSex: voteInput.VoterSex, } voteJSONasBytes, err := json.Marshal(vote) if err != nil { return shim.Error(err.Error()) } // put state for voteCompositeKey err = stub.PutPrivateData("collectionVote", voteCompositeKey, voteJSONasBytes) if err != nil { return shim.Error(err.Error()) } // create a composite key for vote private details collections using the poll ID, voter ID, and salt attrVotePrivateDetailsCompositeKey := []string{voteInput.PollID, voteInput.VoterID, voteInput.Salt} votePrivateDetailsCompositeKey, err := stub.CreateCompositeKey("vote", attrVotePrivateDetailsCompositeKey) if err != nil { return shim.Error("Failed to create composite key for vote private details: " + err.Error()) } votePrivateDetails := &votePrivateDetails { ObjectType: "votePrivateDetails", PollID: voteInput.PollID, VoterID: voteInput.VoterID, Salt: voteInput.Salt, VoteHash: voteInput.VoteHash, } votePrivateDetailsBytes, err := json.Marshal(votePrivateDetails) if err != nil { return shim.Error(err.Error()) } // put state for votePrivateDetailsCompositeKey err = stub.PutPrivateData("collectionVotePrivateDetails", votePrivateDetailsCompositeKey, votePrivateDetailsBytes) if err != nil { return shim.Error(err.Error()) } //register event err = stub.SetEvent("initEvent", []byte{}) if err != nil { return shim.Error(err.Error()) } fmt.Println("- end init vote (success)") return shim.Success(nil) }
/* Copyright 2018 Planet Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package linkin import ( "net/http" "testing" "go.opencensus.io/trace" "go.opencensus.io/trace/propagation" ) func TestSatisfiesHTTPFormat(t *testing.T) { var _ propagation.HTTPFormat = (*HTTPFormat)(nil) } func TestShouldSample(t *testing.T) { cases := []struct { name string flags byte // Only the lowest byte of flags - the rest are unused. shouldSample bool }{ { name: "DebugEnabled", flags: 1, shouldSample: true, }, { name: "SamplingKnownAndEnabled", flags: 6, shouldSample: true, }, { name: "DebugEnabledAndSamplingKnownAndEnabled", flags: 7, shouldSample: true, }, { // Debug mode forces sampling. name: "DebugEnabledAndSamplingKnownAndDisabled", flags: 3, shouldSample: true, }, { name: "SamplingKnownAndDisabled", flags: 2, shouldSample: false, }, { // This flag is undefined. name: "HereBeDragons", flags: 8, shouldSample: false, }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { if shouldSample(tc.flags) != tc.shouldSample { t.Errorf("shouldSample(%08b): want %v, got %v", tc.flags, tc.shouldSample, !tc.shouldSample) } }) } } func requestWithHeader(h string) *http.Request { r, _ := http.NewRequest("GET", "http://example.org", nil) r.Header.Set(l5dHeaderTrace, h) return r } func TestSpanContextFromRequest(t *testing.T) { cases := []struct { name string r *http.Request ok bool sc trace.SpanContext }{ { name: "ValidHeaderWithSamplingEnabled", r: requestWithHeader("9BQdXcDJNdD9O0IEyfZCbzKk2yD11ZLnAAAAAAAAAAY="), ok: true, sc: trace.SpanContext{ TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 0, 50, 164, 219, 32, 245, 213, 146, 231}, SpanID: trace.SpanID{244, 20, 29, 93, 192, 201, 53, 208}, TraceOptions: ocShouldSample, }, }, { name: "ValidHeaderWithoutParentID", r: requestWithHeader("9BQdXcDJNdAAAAAAAAAAADKk2yD11ZLnAAAAAAAAAAYAAAAAAAAAAA=="), ok: true, sc: trace.SpanContext{ TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 0, 50, 164, 219, 32, 245, 213, 146, 231}, SpanID: trace.SpanID{244, 20, 29, 93, 192, 201, 53, 208}, TraceOptions: ocShouldSample, }, }, { name: "ValidHeaderWith128BitTraceID", r: requestWithHeader("9BQdXcDJNdAAAAAAAAAAADKk2yD11ZLnAAAAAAAAAAYAAAAAAAAAAQ=="), ok: true, sc: trace.SpanContext{ TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 1, 50, 164, 219, 32, 245, 213, 146, 231}, SpanID: trace.SpanID{244, 20, 29, 93, 192, 201, 53, 208}, TraceOptions: ocShouldSample, }, }, { name: "ValidHeaderWithSamplingDisabled", r: requestWithHeader("laEAbScFR/gDfE/j8FV/8P8jOugI0dtmAAAAAAAAAAA="), ok: true, sc: trace.SpanContext{ TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 0, 255, 35, 58, 232, 8, 209, 219, 102}, SpanID: trace.SpanID{149, 161, 0, 109, 39, 5, 71, 248}, }, }, { name: "InvalidHeaderEncoding", r: requestWithHeader("PROBABLYNOTBASE64"), ok: false, }, { name: "InvalidHeaderLength", r: requestWithHeader("bmVlZWVyZA=="), ok: false, }, } for _, tc := range cases { f := &HTTPFormat{} t.Run(tc.name, func(t *testing.T) { got, ok := f.SpanContextFromRequest(tc.r) if ok != tc.ok { t.Errorf("t.SpanContextFromRequest(): want ok %v, got %v", tc.ok, ok) } if got != tc.sc { t.Errorf("f.SpanContextFromRequest():\ngot: %+v\nwant: %+v\n", got, tc.sc) } }) } } func TestSpanContextToRequest(t *testing.T) { cases := []struct { name string header string sc trace.SpanContext }{ { name: "ValidHeaderWithSamplingEnabled", header: "9BQdXcDJNdAAAAAAAAAAADKk2yD11ZLnAAAAAAAAAAYAAAAAAAAAAA==", sc: trace.SpanContext{ TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 0, 50, 164, 219, 32, 245, 213, 146, 231}, SpanID: trace.SpanID{244, 20, 29, 93, 192, 201, 53, 208}, TraceOptions: ocShouldSample, }, }, { name: "ValidHeaderWithSamplingDisabled", header: "laEAbScFR/gAAAAAAAAAAP8jOugI0dtmAAAAAAAAAAAAAAAAAAAAAA==", sc: trace.SpanContext{ TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 0, 255, 35, 58, 232, 8, 209, 219, 102}, SpanID: trace.SpanID{149, 161, 0, 109, 39, 5, 71, 248}, }, }, { name: "ValidHeaderWith128BitTraceID", header: "9BQdXcDJNdAAAAAAAAAAADKk2yD11ZLnAAAAAAAAAAYAAAAAAAAAAQ==", sc: trace.SpanContext{ TraceID: trace.TraceID{0, 0, 0, 0, 0, 0, 0, 1, 50, 164, 219, 32, 245, 213, 146, 231}, SpanID: trace.SpanID{244, 20, 29, 93, 192, 201, 53, 208}, TraceOptions: ocShouldSample, }, }, } for _, tc := range cases { f := &HTTPFormat{} t.Run(tc.name, func(t *testing.T) { r, _ := http.NewRequest("GET", "http://example.org", nil) f.SpanContextToRequest(tc.sc, r) got := r.Header.Get(l5dHeaderTrace) if got != tc.header { t.Errorf("f.SpanContextToRequest():\ngot header: %+v\nwant: %+v\n", got, tc.header) } }) } }
package model import ( "gorm.io/gorm" "time" ) const OrderNotifyLogTableName = "order_notify_log" const ( // 通知状态 OrderNotifyStatusNotifying = 0 // 通知中 OrderNotifyStatusSuccess = 1 // 成功 OrderNotifyStatusFail = 2 // 失败 // 通知日志订单类型 NotifyLogOrderTypePay = 1 // 代收订单 NotifyLogOrderTypeTransfer = 2 // 代付订单 ) type OrderNotifyLog struct { Id int64 `db:"id"` OrderNo string `db:"order_no"` // 内部订单号 MerchantOrderNo string `db:"merchant_order_no"` // 商户订单号 Status int64 `db:"status"` // 通知状态(0通知中,1成功,2失败) Result string `db:"result"` // 通知返回的结果 CreateTime int64 `db:"create_time"` // 通知时间 OrderType int64 `db:"order_type"` // 订单类型(1代收订单, 2代付订单) } func (t *OrderNotifyLog) TableName() string { return OrderNotifyLogTableName } func NewOrderNotifyLogModel(db *gorm.DB) *OrderNotifyLogModel { return &OrderNotifyLogModel{db: db} } type OrderNotifyLogModel struct { db *gorm.DB } func (m *OrderNotifyLogModel) Insert(data *OrderNotifyLog) error { data.CreateTime = time.Now().Unix() result := m.db.Create(data) return result.Error } func (m *OrderNotifyLogModel) Update(id int64, data OrderNotifyLog) error { result := m.db.Model(&OrderNotifyLog{}).Where("id=?", id).Updates(&data) return result.Error }
// Copyright 2016-2021, Pulumi Corporation. package schema import ( "fmt" "github.com/pkg/errors" "github.com/pulumi/pulumi/pkg/v3/codegen" pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema" "github.com/pulumi/pulumi/sdk/v3/go/common/resource" "math" "strings" ) type ValidationFailure struct { Path string Reason string } func validatePrimitive(primitiveType string, path string, property resource.PropertyValue) ([]ValidationFailure, error) { // If the property is secret, inspect its element. for property.IsSecret() { property = property.SecretValue().Element } // If the property value is unknown we're done. if property.IsComputed() || property.IsOutput() { return nil, nil } switch primitiveType { case "string": if !property.IsString() { return []ValidationFailure{{Path: path, Reason: fmt.Sprintf("%v must be a string", path)}}, nil } case "integer": if !property.IsNumber() || math.Trunc(property.NumberValue()) != property.NumberValue() { return []ValidationFailure{{Path: path, Reason: fmt.Sprintf("%v must be an integer", path)}}, nil } case "number": if !property.IsNumber() { return []ValidationFailure{{Path: path, Reason: fmt.Sprintf("%v must be a number", path)}}, nil } case "boolean": if !property.IsBool() { return []ValidationFailure{{Path: path, Reason: fmt.Sprintf("%v must be a bool", path)}}, nil } } return nil, nil } func validateProperty(types map[string]CloudAPIType, required codegen.StringSet, spec *pschema.TypeSpec, path string, property resource.PropertyValue) ([]ValidationFailure, error) { // If the property is secret, inspect its element. for property.IsSecret() { property = property.SecretValue().Element } // If the property value is missing and the property is required, issue a "missing required property" error. if required.Has(path) && property.IsNull() { return []ValidationFailure{{Path: path, Reason: fmt.Sprintf("missing required property %v", path)}}, nil } // If the property value is unknown or missing, we're done. if property.IsComputed() || property.IsOutput() || property.IsNull() { return nil, nil } if spec.Ref != "" { if spec.Ref == "pulumi.json#/Any" { return nil, nil } typName := strings.TrimPrefix(spec.Ref, "#/types/") typeSpec, ok := types[typName] if !ok { return nil, errors.Errorf("could not find property type %v in schema", typName) } if typeSpec.Type != "object" { return validatePrimitive(typeSpec.Type, path, property) } if !property.IsObject() { return []ValidationFailure{{Path: path, Reason: fmt.Sprintf("%v must be an object", path)}}, nil } return validateProperties(types, required, typeSpec.Properties, path, property.ObjectValue()) } // Check the type of the property. switch spec.Type { case "array": if !property.IsArray() { return []ValidationFailure{{Path: path, Reason: fmt.Sprintf("%v must be an array", path)}}, nil } var failures []ValidationFailure for i, item := range property.ArrayValue() { itemPath := fmt.Sprintf("%s[%d]", path, i) fs, err := validateProperty(types, required, spec.Items, itemPath, item) if err != nil { return nil, err } failures = append(failures, fs...) } return failures, nil case "object": if !property.IsObject() { return []ValidationFailure{{Path: path, Reason: fmt.Sprintf("%v must be an object", path)}}, nil } var failures []ValidationFailure for k, item := range property.ObjectValue() { itemPath := fmt.Sprintf("%s.%s", path, k) fs, err := validateProperty(types, required, spec.AdditionalProperties, itemPath, item) if err != nil { return nil, err } failures = append(failures, fs...) } return failures, nil default: return validatePrimitive(spec.Type, path, property) } } func validateProperties(types map[string]CloudAPIType, required codegen.StringSet, propertySpecs map[string]pschema.PropertySpec, path string, properties resource.PropertyMap) ([]ValidationFailure, error) { // Do a schema-directed check first. var failures []ValidationFailure remainingProperties := properties.Mappable() for k, propertySpec := range propertySpecs { var propertyPath string if path == "" { propertyPath = k } else { propertyPath = fmt.Sprintf("%s/%s", path, k) } fs, err := validateProperty(types, required, &propertySpec.TypeSpec, propertyPath, properties[resource.PropertyKey(k)]) if err != nil { return nil, err } delete(remainingProperties, k) failures = append(failures, fs...) } // Now check for unexpected properties. for k := range remainingProperties { var propertyPath string if path == "" { propertyPath = string(k) } else { propertyPath = fmt.Sprintf("%s.%s", path, k) } failures = append(failures, ValidationFailure{Path: propertyPath, Reason: fmt.Sprintf("unknown property %v", propertyPath)}) } return failures, nil } func ValidateResource(res *CloudAPIResource, types map[string]CloudAPIType, properties resource.PropertyMap) ([]ValidationFailure, error) { required := codegen.NewStringSet(res.Required...) return validateProperties(types, required, res.Inputs, "", properties) }
package main import ( "fmt" ) func main() { // Print a := 10 fmt.Print("Um print sem quebra de linha") fmt.Println("Um print com quebra de linha") fmt.Printf("Um print com formatação. a = %v\n", a) // Sprint (String Print) b := "Olá" c := "Tudo bem com vc?" sprint1 := fmt.Sprint(b, c) sprint2 := fmt.Sprintf(b, c) sprint3 := fmt.Sprintln(b, c) fmt.Print(sprint1) fmt.Print(sprint2) fmt.Print(sprint3) // Fprint (File Print) // fmt.Fprint }
package main import ( "fmt" ) // 两整型相加 func add(a, b int) (result int) { result = a + b return } // 两整型相减 func minus(a, b int) (result int) { result = a - b return } // 定义了一个两参数都整型,同时返回值也是整型的函数类型FuncTest type FuncTest func(int, int) int func main() { var funcTest FuncTest // 将加法函数赋值给funcTest funcTest = add res1 := funcTest(10, 10) // 等价于 res1 := add(10, 10) fmt.Println("res1 = ", res1) // 将减法函数赋值给funcTest funcTest = minus res2 := funcTest(10, 10) // 等价于 res2 := minus(10, 10) fmt.Println("res2 = ", res2) // 结果为: // res1 = 20 // res2 = 0 }
package xendit import ( "github.com/imrenagi/go-payment" "github.com/imrenagi/go-payment/subscription" ) // NewStatus convert xendit status string to subscripiton status func NewStatus(s string) subscription.Status { switch s { case "ACTIVE": return subscription.StatusActive case "PAUSED": return subscription.StatusPaused default: return subscription.StatusStop } } // NewPaymentSource converts xendit payment method to payment.PaymentType func NewPaymentSource(s string) payment.PaymentType { switch s { case "BCA": return payment.SourceBCAVA case "BRI": return payment.SourceBRIVA case "MANDIRI": return payment.SourceMandiriVA case "BNI": return payment.SourceBNIVA case "PERMATA": return payment.SourcePermataVA case "ALFAMART": return payment.SourceAlfamart case "CREDIT_CARD": return payment.SourceCreditCard case "OVO": return payment.SourceOvo default: return "" } }
package twitterscraper import ( "testing" ) func TestGetTrends(t *testing.T) { trends, err := GetTrends() if err != nil { t.Error(err) } if len(trends) != 10 { t.Error("Expected 10 trends") } }
package config_test import ( "bytes" "encoding/json" "reflect" "testing" . "github.com/andygrunwald/perseus/config" ) func unitTestJSONContent() []byte { b := bytes.NewBufferString(`{ "archive": { "directory": "dist", "format": "tar", "prefix-url": "http://my.url.com/packages/", "skip-dev": true }, "homepage": "http://my.url.com/packages/", "name": "My private php package repositories", "providers": true, "repositories": [ { "type": "git", "url": "http://my.url.com/git-mirror/twig/twig.git" }, { "type": "git", "url": "http://my.url.comgit-mirror/mre/phpench.git" }, { "type": "git", "url": "http://my.url.com/git-mirror/symfony/console.git" } ], "dummy-list": [ "https://www.google.com/", "https://www.github.com/", "https://gobot.io/" ], "require-all": true }`) return b.Bytes() } func TestNewJSONProvider(t *testing.T) { p, err := NewJSONProvider(unitTestJSONContent()) if err != nil { t.Fatalf("Got error: %s", err) } if p == nil { t.Fatal("Got an empty JSON provider. Expected a valid one.") } } func TestNewJSONProvider_EmptyContent(t *testing.T) { p, err := NewJSONProvider([]byte{}) if err == nil { t.Fatal("Expected an error. Got none") } if p != nil { t.Fatal("Got a valid JSON provider. Expected a n empty one.") } } func TestJSONProvider_GetString(t *testing.T) { expected := "http://my.url.com/packages/" p, err := NewJSONProvider(unitTestJSONContent()) if err != nil { t.Fatalf("Got error: %s", err) } got := p.GetString("homepage") if got != expected { t.Fatalf("Got different value than expected. Expected %s, got %s", expected, got) } } func TestJSONProvider_GetString_NotExists(t *testing.T) { expected := "http://my.url.com/packages/" p, err := NewJSONProvider(unitTestJSONContent()) if err != nil { t.Fatalf("Got error: %s", err) } got := p.GetString("not-exists") if got != "" { t.Fatalf("Got different value than expected. Expected an empty string, got %s", expected, got) } } func TestJSONProvider_Get(t *testing.T) { c := unitTestJSONContent() b := make(map[string]*json.RawMessage) err := json.Unmarshal(c, &b) if err != nil { t.Fatalf("Got error while creating json.RawMessage dummy: %s", err) } expected := b["homepage"] p, err := NewJSONProvider(c) if err != nil { t.Fatalf("Got error while creating new JSON provier: %s", err) } got := p.Get("homepage") if !reflect.DeepEqual(got, expected) { t.Fatalf("Got different value than expected. Expected %+v, got %+v", expected, got) } } func TestJSONProvider_Get_NotExists(t *testing.T) { p, err := NewJSONProvider(unitTestJSONContent()) if err != nil { t.Fatalf("Got error while creating new JSON provier: %s", err) } got := p.Get("not-exists") if got.(*json.RawMessage) != nil { t.Fatalf("Got different value than expected. Expected nil, got %+v", got.(*json.RawMessage)) } } func TestJSONProvider_GetContentMap(t *testing.T) { c := unitTestJSONContent() b := make(map[string]*json.RawMessage) err := json.Unmarshal(c, &b) if err != nil { t.Fatalf("Got error while creating json.RawMessage dummy: %s", err) } p, err := NewJSONProvider(c) if err != nil { t.Fatalf("Got error while creating new JSON provier: %s", err) } m := p.GetContentMap() if !reflect.DeepEqual(*b["homepage"], m["homepage"]) { t.Fatalf("Homepage -> Got different value than expected. Expected %+v, got %+v", b["homepage"], m["homepage"]) } if !reflect.DeepEqual(*b["archive"], m["archive"]) { t.Fatalf("Archive -> Got different value than expected. Expected %+v, got %+v", b["archive"], m["archive"]) } if !reflect.DeepEqual(*b["repositories"], m["repositories"]) { t.Fatalf("Repositories -> Got different value than expected. Expected %+v, got %+v", b["repositories"], m["repositories"]) } } func TestJSONProvider_GetStringSlice(t *testing.T) { expected := []string{ "https://www.google.com/", "https://www.github.com/", "https://gobot.io/", } p, err := NewJSONProvider(unitTestJSONContent()) if err != nil { t.Fatalf("Got error while creating new JSON provier: %s", err) } got := p.GetStringSlice("dummy-list") if !reflect.DeepEqual(got, expected) { t.Fatalf("Got different value than expected. Expected %+v, got %+v", expected, got) } } func TestJSONProvider_GetStringSlice_NotExists(t *testing.T) { var expected []string p, err := NewJSONProvider(unitTestJSONContent()) if err != nil { t.Fatalf("Got error while creating new JSON provier: %s", err) } got := p.GetStringSlice("not-exists") if !reflect.DeepEqual(got, expected) { t.Fatalf("Got different value than expected. Expected %+v, got %+v", expected, got) } }
package main import "fmt" var slice []byte func main() { slice = make([]byte, 12) go func() { slice[0] = byte('H') }() slice[3] = byte('e') fmt.Println(slice) }
package mtest import ( "encoding/json" "os" "strconv" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("assets", func() { It("should work as expected", func() { f := localTempFile("test") defer os.Remove(f.Name()) By("Uploading an asset") sabactl("assets", "upload", "test", f.Name()) By("Checking all servers pull the asset") Eventually(func() bool { var info struct { Urls []string `json:"urls"` } stdout := sabactl("assets", "info", "test") err := json.Unmarshal(stdout, &info) if err != nil { return false } return len(info.Urls) == 3 }).Should(BeTrue()) By("Removing the asset from the index") sabactl("assets", "delete", "test") By("Checking all servers remove the asset") Eventually(func() bool { for _, h := range []string{host1, host2, host3} { stdout, _, err := execAt(h, "ls", "/var/lib/sabakan/assets") if err != nil || len(stdout) > 0 { return false } } return true }).Should(BeTrue()) By("Stopping host2 sabakan") Expect(stopHost2Sabakan()).To(Succeed()) By("Adding two assets") f1 := localTempFile("updated 1") defer os.Remove(f1.Name()) sabactl("assets", "upload", "test2", f1.Name()) f2 := localTempFile("updated 2") defer os.Remove(f2.Name()) sabactl("assets", "upload", "test2", f2.Name()) By("Getting the current revision") stdout := etcdctl("get", "/", "-w=json") v := &struct { Header struct { Revision int `json:"revision"` } `json:"header"` }{} Expect(json.Unmarshal(stdout, v)).To(Succeed()) currentRevision := v.Header.Revision By("Executing compaction") etcdctl("compaction", "--physical=true", strconv.Itoa(currentRevision)) By("Restarting host2 sabakan") Expect(startHost2Sabakan()).To(Succeed()) By("Confirming that sabakan can get the latest asset again") Eventually(func() bool { var info struct { Urls []string `json:"urls"` } stdout := sabactl("assets", "info", "test2") err := json.Unmarshal(stdout, &info) if err != nil { return false } return len(info.Urls) == 3 }).Should(BeTrue()) }) }) func stopHost2Sabakan() error { host2Client := sshClients[host2] sess, err := host2Client.NewSession() if err != nil { return err } defer sess.Close() return sess.Run("sudo systemctl stop sabakan.service") } func startHost2Sabakan() error { host2Client := sshClients[host2] sess, err := host2Client.NewSession() if err != nil { return err } defer sess.Close() return sess.Run("sudo systemd-run --unit=sabakan.service /data/sabakan -config-file /etc/sabakan.yml") }
package posts import ( "appointy/dbservice" "context" "sync" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" ) var getPostLock sync.Mutex func GetPost(id string) Post { getPostLock.Lock() defer getPostLock.Unlock() var post Post client, _ := dbservice.GetMongoClient() var postCollection = client.Database(dbservice.DB).Collection(dbservice.POSTS_COLLECTION) filter := bson.D{primitive.E{Key: "id", Value: id}} postCollection.FindOne(context.TODO(), filter).Decode(&post) return post }
package swarm import ( "io" "net" "sync" "time" "xd/lib/bittorrent" "xd/lib/bittorrent/extensions" "xd/lib/common" "xd/lib/log" ) const DefaultMaxParallelRequests = 2 // a peer connection type PeerConn struct { inbound bool closing bool c net.Conn id common.PeerID t *Torrent send chan *common.WireMessage bf *bittorrent.Bitfield peerChoke bool peerInterested bool usChoke bool usInterseted bool Done func() keepalive *time.Ticker lastSend time.Time tx float32 lastRecv time.Time rx float32 downloading []*common.PieceRequest ourOpts *extensions.ExtendedOptions theirOpts *extensions.ExtendedOptions MaxParalellRequests int access sync.Mutex } // get stats for this connection func (c *PeerConn) Stats() (st *PeerConnStats) { st = new(PeerConnStats) st.TX = c.tx st.RX = c.rx st.Addr = c.c.RemoteAddr().String() st.ID = c.id.String() return } func makePeerConn(c net.Conn, t *Torrent, id common.PeerID, ourOpts *extensions.ExtendedOptions) *PeerConn { p := new(PeerConn) p.c = c p.t = t p.ourOpts = ourOpts p.peerChoke = true p.usChoke = true copy(p.id[:], id[:]) p.MaxParalellRequests = DefaultMaxParallelRequests p.send = make(chan *common.WireMessage, 8) p.keepalive = time.NewTicker(time.Minute) p.downloading = []*common.PieceRequest{} // TODO: hard coded return p } func (c *PeerConn) start() { go c.runReader() go c.runWriter() } // queue a send of a bittorrent wire message to this peer func (c *PeerConn) Send(msg *common.WireMessage) { if !c.closing { c.send <- msg } } // recv a bittorrent wire message (blocking) func (c *PeerConn) Recv() (msg *common.WireMessage, err error) { msg = new(common.WireMessage) err = msg.Recv(c.c) log.Debugf("got %d bytes from %s", msg.Len(), c.id) now := time.Now() c.rx = float32(msg.Len()) / float32(now.Unix()-c.lastRecv.Unix()) c.lastRecv = now return } // send choke func (c *PeerConn) Choke() { if !c.usChoke { log.Debugf("choke peer %s", c.id.String()) c.Send(common.NewWireMessage(common.Choke, nil)) c.usChoke = true } } // send unchoke func (c *PeerConn) Unchoke() { if c.usChoke { log.Debugf("unchoke peer %s", c.id.String()) c.Send(common.NewWireMessage(common.UnChoke, nil)) c.usChoke = false } } func (c *PeerConn) gotDownload(p *common.PieceData) { c.access.Lock() var downloading []*common.PieceRequest for _, r := range c.downloading { if r.Matches(p) { c.t.pt.handlePieceData(p) } else { downloading = append(downloading, r) } } c.downloading = downloading c.access.Unlock() } func (c *PeerConn) cancelDownload(req *common.PieceRequest) { c.access.Lock() var downloading []*common.PieceRequest for _, r := range c.downloading { if r.Equals(req) { c.t.pt.canceledRequest(r) } else { downloading = append(downloading, r) } } c.downloading = downloading c.access.Unlock() } func (c *PeerConn) numDownloading() int { c.access.Lock() i := len(c.downloading) c.access.Unlock() return i } func (c *PeerConn) queueDownload(req *common.PieceRequest) { if c.closing { c.clearDownloading() return } c.access.Lock() c.downloading = append(c.downloading, req) log.Debugf("ask %s for %d %d %d", c.id.String(), req.Index, req.Begin, req.Length) c.Send(req.ToWireMessage()) c.access.Unlock() } func (c *PeerConn) clearDownloading() { c.access.Lock() for _, r := range c.downloading { c.t.pt.canceledRequest(r) } c.downloading = []*common.PieceRequest{} c.access.Unlock() } func (c *PeerConn) HasPiece(piece uint32) bool { if c.bf == nil { // no bitfield return false } return c.bf.Has(piece) } // return true if this peer is choking us otherwise return false func (c *PeerConn) RemoteChoking() bool { return c.peerChoke } // return true if we are choking the remote peer otherwise return false func (c *PeerConn) Chocking() bool { return c.usChoke } func (c *PeerConn) remoteUnchoke() { if !c.peerChoke { log.Warnf("remote peer %s sent multiple unchokes", c.id.String()) } c.peerChoke = false log.Debugf("%s unchoked us", c.id.String()) } func (c *PeerConn) remoteChoke() { if c.peerChoke { log.Warnf("remote peer %s sent multiple chokes", c.id.String()) } c.peerChoke = true log.Debugf("%s choked us", c.id.String()) } func (c *PeerConn) markInterested() { c.peerInterested = true log.Debugf("%s is interested", c.id.String()) } func (c *PeerConn) markNotInterested() { c.peerInterested = false log.Debugf("%s is not interested", c.id.String()) } func (c *PeerConn) Close() { if c.closing { return } c.closing = true for _, r := range c.downloading { c.t.pt.canceledRequest(r) } c.downloading = nil c.keepalive.Stop() log.Debugf("%s closing connection", c.id.String()) if c.send != nil { chnl := c.send c.send = nil close(chnl) } c.c.Close() if c.inbound { c.t.removeIBConn(c) } else { c.t.removeOBConn(c) } } // run read loop func (c *PeerConn) runReader() { var err error for err == nil { msg, e := c.Recv() err = e if err == nil { if msg.KeepAlive() { log.Debugf("keepalive from %s", c.id) continue } msgid := msg.MessageID() log.Debugf("%s from %s", msgid.String(), c.id.String()) if msgid == common.BitField { isnew := false if c.bf == nil { isnew = true } c.bf = bittorrent.NewBitfield(c.t.MetaInfo().Info.NumPieces(), msg.Payload()) log.Debugf("got bitfield from %s", c.id.String()) // TODO: determine if we are really interested m := common.NewInterested() c.Send(m) if isnew { go c.runDownload() } continue } if msgid == common.Choke { c.remoteChoke() continue } if msgid == common.UnChoke { c.remoteUnchoke() continue } if msgid == common.Interested { c.markInterested() c.Unchoke() continue } if msgid == common.NotInterested { c.markNotInterested() continue } if msgid == common.Request { ev := msg.GetPieceRequest() c.t.onPieceRequest(c, ev) continue } if msgid == common.Piece { d := msg.GetPieceData() if d == nil { log.Warnf("invalid piece data message from %s", c.id.String()) c.Close() } else { c.gotDownload(d) } continue } if msgid == common.Have && c.bf != nil { // update bitfield idx := msg.GetHave() c.bf.Set(idx) if c.t.Bitfield().Has(idx) { // not interested c.Send(common.NewNotInterested()) } else { c.Send(common.NewInterested()) } continue } if msgid == common.Cancel { // TODO: check validity r := msg.GetPieceRequest() c.t.pt.canceledRequest(r) continue } if msgid == common.Extended { // handle extended options opts := extensions.FromWireMessage(msg) if opts == nil { log.Warnf("failed to parse extended options for %s", c.id.String()) } else { c.handleExtendedOpts(opts) } } } } if err != io.EOF { log.Errorf("%s read error: %s", c.id, err) } c.Close() } func (c *PeerConn) handleExtendedOpts(opts *extensions.ExtendedOptions) { log.Debugf("got extended opts from %s: %s", c.id.String(), opts) } func (c *PeerConn) sendKeepAlive() error { tm := time.Now().Add(0 - (time.Minute * 2)) if c.lastSend.Before(tm) { log.Debugf("send keepalive to %s", c.id.String()) return common.KeepAlive().Send(c.c) } return nil } // run write loop func (c *PeerConn) runWriter() { var err error for err == nil && !c.closing { select { case <-c.keepalive.C: err = c.sendKeepAlive() if err != nil { break } case msg, ok := <-c.send: if ok { now := time.Now() c.tx = float32(msg.Len()) / float32(now.Unix()-c.lastSend.Unix()) c.lastSend = now if c.RemoteChoking() && msg.MessageID() == common.Request { // drop log.Debugf("drop request because choke") r := msg.GetPieceRequest() c.cancelDownload(r) } else { log.Debugf("writing %d bytes", msg.Len()) err = msg.Send(c.c) log.Debugf("wrote message %s %d bytes", msg.MessageID(), msg.Len()) } } else { break } } } c.Close() } // run download loop func (c *PeerConn) runDownload() { pendingTry := 0 for !c.t.Done() && c.send != nil { if c.RemoteChoking() { time.Sleep(time.Second) continue } // pending request p := c.numDownloading() if p >= c.MaxParalellRequests { log.Debugf("too many pending requests %d, waiting", p) if pendingTry > 5 { c.Close() return } pendingTry++ time.Sleep(time.Second * 10) continue } pendingTry = 0 r := c.t.pt.nextRequestForDownload(c.bf) if r == nil { log.Debugf("no next piece to download for %s", c.id.String()) time.Sleep(time.Second) } else { c.queueDownload(r) } } if c.send == nil { c.Close() log.Debugf("peer %s disconnected trying reconnect", c.id.String()) return } log.Debugf("peer %s is 'done'", c.id.String()) // done downloading if c.Done != nil { c.Done() } }
package hot100 import ( "fmt" "testing" "time" ) func Test_permute(t *testing.T) { fmt.Println(permute([]int{1, 2, 3})) } func Test_asssd(t *testing.T) { d := make(chan int, 10) go func() { d <- 1 d <- 2 }() go func() { for v := range d { fmt.Println(v) } }() time.Sleep(time.Second*2) d<-33 time.Sleep(time.Second * 10) }
package middleware import ( "github.com/dgrijalva/jwt-go" "github.com/gin-gonic/gin" "net/http" "server-monitor-admin/global" "server-monitor-admin/global/response" "server-monitor-admin/utils" "strconv" ) func JwtAuth() gin.HandlerFunc { return func(context *gin.Context) { auth := context.Request.Header.Get("X-Token") if len(auth) == 0 { context.Abort() response.FailCodeMsg(http.StatusUnauthorized, "请重新登录", context) } // 校验token c, err := parseToken(auth) if c != nil { userId, _ := strconv.ParseInt(c.Id, 10, 64) context.Set(utils.USER_ID_FILED, userId) } if err != nil { context.Abort() response.FailCodeMsg(http.StatusUnauthorized, "token 过期"+err.Error(), context) } context.Next() } } //解析token func parseToken(token string) (*jwt.StandardClaims, error) { jwtToken, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, func(token *jwt.Token) (i interface{}, e error) { return []byte(global.CONFIG.Jwt.Secret), nil }) if err == nil && jwtToken != nil { if claim, ok := jwtToken.Claims.(*jwt.StandardClaims); ok && jwtToken.Valid { return claim, nil } } return nil, err }
package util import ( "strings" ) const notationChars = "BCDGHIJKLMNOPQRSTUVXYZ" func Num2Char(num int) string { out := &strings.Builder{} encodeNum(num, out) return out.String() } func encodeNum(num int, out *strings.Builder) { if num/len(notationChars) != 0 { encodeNum(num/len(notationChars), out) } out.WriteByte(notationChars[num%len(notationChars)]) }
package handlers import ( "forum/internal/handlers/backend" "github.com/gin-gonic/gin" ) func backendRouter(r *gin.RouterGroup) { r.GET("/welcome", backend.Hello) }
package sheet_logic import ( "hub/sheet_logic/sheet_logic_types" "testing" ) func TestIntModulo(t *testing.T) { uut := NewIntModulo(variableName) grammarElementScenario(t, uut.GrammarElement, sheet_logic_types.IntModulo) uut.SetLeftArg(NewIntConstant(variableName, 5)) uut.SetRightArg(NewIntConstant(variableName, 2)) assertCalculatesToInt( t, uut, 1, noGrammarContext, "IntModulo.CalculateInt") uut.SetLeftArg(NewEmptyIntExpression()) assertCalculatesToIntFails( t, uut, noGrammarContext, "IntModulo.CalculateInt fails when argLeft missing") uut.SetLeftArg(NewIntConstant(variableName, 5)) uut.SetRightArg(NewEmptyIntExpression()) assertCalculatesToIntFails( t, uut, noGrammarContext, "IntModulo.CalculateInt fails when argRight missing") uut.SetRightArg(NewIntConstant(variableName, 0)) assertCalculatesToIntFails( t, uut, noGrammarContext, "IntModulo.CalculateInt fails when dividing by zero") }
/* * EVE Swagger Interface * * An OpenAPI for EVE Online * * OpenAPI spec version: 0.4.1.dev1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ package swagger import ( "time" ) // 200 ok object type GetCharactersCharacterIdOk struct { // The character's alliance ID AllianceId int32 `json:"alliance_id,omitempty"` // ancestry_id integer AncestryId int32 `json:"ancestry_id,omitempty"` // Creation date of the character Birthday time.Time `json:"birthday,omitempty"` // bloodline_id integer BloodlineId int32 `json:"bloodline_id,omitempty"` // The character's corporation ID CorporationId int32 `json:"corporation_id,omitempty"` // description string Description string `json:"description,omitempty"` // gender string Gender string `json:"gender,omitempty"` // name string Name string `json:"name,omitempty"` // race_id integer RaceId int32 `json:"race_id,omitempty"` // security_status number SecurityStatus float32 `json:"security_status,omitempty"` }
package main import "fmt" func editMap(m map[int]int) { m[3] = 8 m[4] = 9 } func editSlice(s []int) { s = append(s, 5) s = append(s, 9) } func main() { m := make(map[int]int, 0) m[1] = 5 m[2] = 3 fmt.Printf("%v\n", m) editMap(m) fmt.Printf("%v\n", m) s := make([]int, 2) s[0] = 2 s[1] = 5 fmt.Printf("%v\n", s) editSlice(s) fmt.Printf("%v\n", s) }
// Copyright 2013 Benjamin Gentil. All rights reserved. // license can be found in the LICENSE file (MIT License) package zlang import ( "fmt" ) func runTest(name, src string) { l := NewLexer(name, src) for { it := l.NextItem() fmt.Println(it.Token, "\t\t", it) if it.Token == TOK_EOF || it.Token == TOK_ERROR { break } } } func ExampleLexArray() { src := ` main is func() int { // int a[][] // a[0][0] = 1 // a[1][0] = 2, a[1][1] = 3 // a[2][0] = 4 a is [[1], [2, 3], [4]] f is [f(), f(), 1] z is [0x5A, 0x6C, 0x61, 0x6E, 0x67, 0x21] a[2][0] is 3 return z[0] } ` runTest("ExampleLexArray", src) //output: // //ENDL "\n" //IDENTIFIER "main" //is "is" //func "func" //( "(" //) ")" //IDENTIFIER "int" //{ "{" //ENDL "\n" //COMMENT "// int a[]"... //ENDL "\n" //COMMENT "// a[0][0]"... //ENDL "\n" //COMMENT "// a[1][0]"... //ENDL "\n" //COMMENT "// a[2][0]"... //ENDL "\n" //IDENTIFIER "a" //is "is" //[ "[" //[ "[" //INT "1" //] "]" //, "," //[ "[" //INT "2" //, "," //INT "3" //] "]" //, "," //[ "[" //INT "4" //] "]" //] "]" //ENDL "\n" //ENDL "\n" //IDENTIFIER "f" //is "is" //[ "[" //IDENTIFIER "f" //( "(" //) ")" //, "," //IDENTIFIER "f" //( "(" //) ")" //, "," //INT "1" //] "]" //ENDL "\n" //ENDL "\n" //IDENTIFIER "z" //is "is" //[ "[" //BYTE "0x5A" //, "," //BYTE "0x6C" //, "," //BYTE "0x61" //, "," //BYTE "0x6E" //, "," //BYTE "0x67" //, "," //BYTE "0x21" //] "]" //ENDL "\n" //ENDL "\n" //IDENTIFIER "a" //[ "[" //INT "2" //] "]" //[ "[" //INT "0" //] "]" //is "is" //INT "3" //ENDL "\n" //ENDL "\n" //return "return" //IDENTIFIER "z" //[ "[" //INT "0" //] "]" //ENDL "\n" //} "}" //ENDL "\n" //EOF EOF } func ExampleLexBitOps() { src := ` main is func() int { i is 4 lshift 1 if i nand 4 { i is 4 rshift 1 } i is 4 xor 5 if i nor 4 { } } ` runTest("ExampleLexBitOps", src) //output: // //ENDL "\n" //IDENTIFIER "main" //is "is" //func "func" //( "(" //) ")" //IDENTIFIER "int" //{ "{" //ENDL "\n" //IDENTIFIER "i" //is "is" //INT "4" //lshift "lshift" //INT "1" //ENDL "\n" //ENDL "\n" //if "if" //IDENTIFIER "i" //nand "nand" //INT "4" //{ "{" //ENDL "\n" //IDENTIFIER "i" //is "is" //INT "4" //rshift "rshift" //INT "1" //ENDL "\n" //} "}" //ENDL "\n" //ENDL "\n" //IDENTIFIER "i" //is "is" //INT "4" //xor "xor" //INT "5" //ENDL "\n" //ENDL "\n" //if "if" //IDENTIFIER "i" //nor "nor" //INT "4" //{ "{" //ENDL "\n" //ENDL "\n" //} "}" //ENDL "\n" //} "}" //ENDL "\n" //EOF EOF } func ExampleLexOperator() { src := ` main is func() int { if 4 eq 4 { // eq } if 4 neq 5 { // neq } if 4 lt 5 { // lt } if 4 le 5 { // le } if 4 gt 5 { // gt } if 4 ge 5 { // ge } if 4 ge 5 or 4 le 5 and 4 eq 4 { // ge } if not 0 { } } ` runTest("ExampleLexOperator", src) //output: // //ENDL "\n" //IDENTIFIER "main" //is "is" //func "func" //( "(" //) ")" //IDENTIFIER "int" //{ "{" //ENDL "\n" //if "if" //INT "4" //eq "eq" //INT "4" //{ "{" //ENDL "\n" //COMMENT "// eq" //ENDL "\n" //} "}" //ENDL "\n" //if "if" //INT "4" //neq "neq" //INT "5" //{ "{" //ENDL "\n" //COMMENT "// neq" //ENDL "\n" //} "}" //ENDL "\n" //if "if" //INT "4" //lt "lt" //INT "5" //{ "{" //ENDL "\n" //COMMENT "// lt" //ENDL "\n" //} "}" //ENDL "\n" //if "if" //INT "4" //le "le" //INT "5" //{ "{" //ENDL "\n" //COMMENT "// le" //ENDL "\n" //} "}" //ENDL "\n" //if "if" //INT "4" //gt "gt" //INT "5" //{ "{" //ENDL "\n" //COMMENT "// gt" //ENDL "\n" //} "}" //ENDL "\n" //if "if" //INT "4" //ge "ge" //INT "5" //{ "{" //ENDL "\n" //COMMENT "// ge" //ENDL "\n" //} "}" //ENDL "\n" //if "if" //INT "4" //ge "ge" //INT "5" //or "or" //INT "4" //le "le" //INT "5" //and "and" //INT "4" //eq "eq" //INT "4" //{ "{" //ENDL "\n" //COMMENT "// ge" //ENDL "\n" //} "}" //ENDL "\n" //if "if" //not "not" //INT "0" //{ "{" //ENDL "\n" //ENDL "\n" //} "}" //ENDL "\n" //} "}" //ENDL "\n" //EOF EOF } func ExampleLexWhile() { src := ` main is func() int { while { while 4 neq 5 { break } break } } ` runTest("ExampleLexWhile", src) //output: // //ENDL "\n" //IDENTIFIER "main" //is "is" //func "func" //( "(" //) ")" //IDENTIFIER "int" //{ "{" //ENDL "\n" //while "while" //{ "{" //ENDL "\n" //while "while" //INT "4" //neq "neq" //INT "5" //{ "{" //ENDL "\n" //break "break" //ENDL "\n" //} "}" //ENDL "\n" //break "break" //ENDL "\n" //} "}" //ENDL "\n" //} "}" //ENDL "\n" //EOF EOF } func ExampleLexBool() { src := ` foo is func(int64 i) bool { if i gt 1 { return true } return false } main is func() int { if foo() { return 1 } return 0 } ` runTest("ExampleLexBool", src) //output: // //ENDL "\n" //IDENTIFIER "foo" //is "is" //func "func" //( "(" //IDENTIFIER "int64" //IDENTIFIER "i" //) ")" //IDENTIFIER "bool" //{ "{" //ENDL "\n" //if "if" //IDENTIFIER "i" //gt "gt" //INT "1" //{ "{" //ENDL "\n" //return "return" //BOOL "true" //ENDL "\n" //} "}" //ENDL "\n" //return "return" //BOOL "false" //ENDL "\n" //} "}" //ENDL "\n" //ENDL "\n" //IDENTIFIER "main" //is "is" //func "func" //( "(" //) ")" //IDENTIFIER "int" //{ "{" //ENDL "\n" //if "if" //IDENTIFIER "foo" //( "(" //) ")" //{ "{" //ENDL "\n" //return "return" //INT "1" //ENDL "\n" //} "}" //ENDL "\n" //return "return" //INT "0" //ENDL "\n" //} "}" //ENDL "\n" //EOF EOF } func ExampleLexInteger() { src := ` foo is func(int64 i) { return i } square is func(int32 x) int32 { return x*x } main is func() int { result is (square(2)+1)*2 result is 1+20/square(2) return result } ` runTest("ExampleLexInteger", src) //output: // //ENDL "\n" //IDENTIFIER "foo" //is "is" //func "func" //( "(" //IDENTIFIER "int64" //IDENTIFIER "i" //) ")" //{ "{" //ENDL "\n" //return "return" //IDENTIFIER "i" //ENDL "\n" //} "}" //ENDL "\n" //ENDL "\n" //IDENTIFIER "square" //is "is" //func "func" //( "(" //IDENTIFIER "int32" //IDENTIFIER "x" //) ")" //IDENTIFIER "int32" //{ "{" //ENDL "\n" //return "return" //IDENTIFIER "x" //* "*" //IDENTIFIER "x" //ENDL "\n" //} "}" //ENDL "\n" //ENDL "\n" //IDENTIFIER "main" //is "is" //func "func" //( "(" //) ")" //IDENTIFIER "int" //{ "{" //ENDL "\n" //IDENTIFIER "result" //is "is" //( "(" //IDENTIFIER "square" //( "(" //INT "2" //) ")" //+ "+" //INT "1" //) ")" //* "*" //INT "2" //ENDL "\n" //IDENTIFIER "result" //is "is" //INT "1" //+ "+" //INT "20" /// "/" //IDENTIFIER "square" //( "(" //INT "2" //) ")" //ENDL "\n" //return "return" //IDENTIFIER "result" //ENDL "\n" //} "}" //ENDL "\n" //EOF EOF } func ExampleLexFloat() { src := ` foo is func(float64 i) { return i } square is func(float32 x) float32 { return x*x } main is func() float { result is (square(2.)+1.0)*2. result is 1.0+20./square(2.0) return 23.3. } ` runTest("ExampleLexFloat", src) //output: // //ENDL "\n" //IDENTIFIER "foo" //is "is" //func "func" //( "(" //IDENTIFIER "float64" //IDENTIFIER "i" //) ")" //{ "{" //ENDL "\n" //return "return" //IDENTIFIER "i" //ENDL "\n" //} "}" //ENDL "\n" //ENDL "\n" //IDENTIFIER "square" //is "is" //func "func" //( "(" //IDENTIFIER "float32" //IDENTIFIER "x" //) ")" //IDENTIFIER "float32" //{ "{" //ENDL "\n" //return "return" //IDENTIFIER "x" //* "*" //IDENTIFIER "x" //ENDL "\n" //} "}" //ENDL "\n" //ENDL "\n" //IDENTIFIER "main" //is "is" //func "func" //( "(" //) ")" //IDENTIFIER "float" //{ "{" //ENDL "\n" //IDENTIFIER "result" //is "is" //( "(" //IDENTIFIER "square" //( "(" //FLOAT "2." //) ")" //+ "+" //FLOAT "1.0" //) ")" //* "*" //FLOAT "2." //ENDL "\n" //IDENTIFIER "result" //is "is" //FLOAT "1.0" //+ "+" //FLOAT "20." /// "/" //IDENTIFIER "square" //( "(" //FLOAT "2.0" //) ")" //ENDL "\n" //return "return" //ERROR misformated float 23.3. } func ExampleLexFunction() { src := ` extern puts(string) extern fib_c(int, @int, int) int extern foo(@int) @ square is func(int x) @int { // comment return x*x } main is func() int { puts("Hello, 世界") // support UTF-8 encoding // result = square result is square(2) return result } ` runTest("ExampleLexFunction", src) //output: // //ENDL "\n" //extern "extern" //IDENTIFIER "puts" //( "(" //IDENTIFIER "string" //) ")" //ENDL "\n" //extern "extern" //IDENTIFIER "fib_c" //( "(" //IDENTIFIER "int" //, "," //IDENTIFIER "@int" //, "," //IDENTIFIER "int" //) ")" //IDENTIFIER "int" //ENDL "\n" //extern "extern" //IDENTIFIER "foo" //( "(" //IDENTIFIER "@int" //) ")" //IDENTIFIER "@" //ENDL "\n" //ENDL "\n" //IDENTIFIER "square" //is "is" //func "func" //( "(" //IDENTIFIER "int" //IDENTIFIER "x" //) ")" //IDENTIFIER "@int" //{ "{" //COMMENT "// comment" //ENDL "\n" //return "return" //IDENTIFIER "x" //* "*" //IDENTIFIER "x" //ENDL "\n" //} "}" //ENDL "\n" //ENDL "\n" //IDENTIFIER "main" //is "is" //func "func" //( "(" //) ")" //IDENTIFIER "int" //{ "{" //ENDL "\n" //IDENTIFIER "puts" //( "(" //STRING "Hello, 世界"... //) ")" //COMMENT "// support"... //ENDL "\n" //ENDL "\n" //COMMENT "// result "... //ENDL "\n" //IDENTIFIER "result" //is "is" //IDENTIFIER "square" //( "(" //INT "2" //) ")" //ENDL "\n" //ENDL "\n" //return "return" //IDENTIFIER "result" //ENDL "\n" //} "}" //ENDL "\n" //EOF EOF } func ExampleLexComment() { src := ` /* multiline comment */ extern puts(string) extern fib_c(int, int/* test */, int) int // pointer support extern foo(@int) @ square is func(int x) int { // comment return x*x } main is func() int { puts("Hello, 世界") // support UTF-8 encoding // result = square result is square(2) /*if result neq 4 { println("FAILURE: \"not 4\"") } else { println("SUCCESS") }*/ fib_c(4, 1, 0) return result } ` runTest("ExampleLexComment", src) // output: // //ENDL "\n" //COMMENT "/*\n\t\tmulti"... //ENDL "\n" //extern "extern" //IDENTIFIER "puts" //( "(" //IDENTIFIER "string" //) ")" //ENDL "\n" //ENDL "\n" //extern "extern" //IDENTIFIER "fib_c" //( "(" //IDENTIFIER "int" //, "," //IDENTIFIER "int" //COMMENT "/* test */" //, "," //IDENTIFIER "int" //) ")" //IDENTIFIER "int" //ENDL "\n" //ENDL "\n" //COMMENT "// pointer"... //ENDL "\n" //extern "extern" //IDENTIFIER "foo" //( "(" //IDENTIFIER "@int" //) ")" //IDENTIFIER "@" //ENDL "\n" //ENDL "\n" //IDENTIFIER "square" //is "is" //func "func" //( "(" //IDENTIFIER "int" //IDENTIFIER "x" //) ")" //IDENTIFIER "int" //{ "{" //COMMENT "// comment" //ENDL "\n" //return "return" //IDENTIFIER "x" //* "*" //IDENTIFIER "x" //ENDL "\n" //} "}" //ENDL "\n" //ENDL "\n" //IDENTIFIER "main" //is "is" //func "func" //( "(" //) ")" //IDENTIFIER "int" //{ "{" //ENDL "\n" //IDENTIFIER "puts" //( "(" //STRING "Hello, 世界"... //) ")" //COMMENT "// support"... //ENDL "\n" //ENDL "\n" //COMMENT "// result "... //ENDL "\n" //IDENTIFIER "result" //is "is" //IDENTIFIER "square" //( "(" //INT "2" //) ")" //ENDL "\n" //COMMENT "/*if resul"... //ENDL "\n" //ENDL "\n" //IDENTIFIER "fib_c" //( "(" //INT "4" //, "," //INT "1" //, "," //INT "0" //) ")" //ENDL "\n" //ENDL "\n" //return "return" //IDENTIFIER "result" //ENDL "\n" //} "}" //ENDL "\n" //EOF EOF }
package terminfo var rxvtUnicode = Terminfo{ Name: "rxvt-unicode", Keys: [maxKeys]string{ "", "\x1b[11~", "\x1b[12~", "\x1b[13~", "\x1b[14~", "\x1b[15~", "\x1b[17~", "\x1b[18~", "\x1b[19~", "\x1b[20~", "\x1b[21~", "\x1b[23~", "\x1b[24~", "\x1b[2~", "\x1b[3~", "\x1b[7~", "\x1b[8~", "\x1b[5~", "\x1b[6~", "\x1b[A", "\x1b[B", "\x1b[D", "\x1b[C", }, Funcs: [maxFuncs]string{ "", "\x1b[?1049h", "\x1b[r\x1b[?1049l", "\x1b[?25h", "\x1b[?25l", "\x1b[H\x1b[2J", "\x1b[m\x1b(B", "\x1b[4m", "\x1b[1m", "\x1b[5m", "\x1b[7m", "\x1b=", "\x1b>", "\x1b[?1000h\x1b[?1002h\x1b[?1015h\x1b[?1006h", "\x1b[?1006l\x1b[?1015l\x1b[?1002l\x1b[?1000l", }} func init() { builtins["rxvt-unicode"] = &rxvtUnicode compatTable = append(compatTable, compatEntry{"rxvt", &rxvtUnicode}) }
package main import ( "fmt" "time" context "golang.org/x/net/context" ) func test() { gen := func(ctx context.Context) <-chan int { dest := make(chan int, 3) n := 1 go func() { for { select { case <-ctx.Done(): fmt.Println("ordered to stop") return case dest <- n: fmt.Printf("can gen number: %d\n", n) n++ } } }() return dest } ctx, cancel := context.WithCancel(context.Background()) defer cancel() for n := range gen(ctx) { fmt.Println(n) if n == 5 { break } time.Sleep(3000 * time.Millisecond) } } func main() { test() time.Sleep(3000 * time.Millisecond) }
package clientserverpair import ( "bytes" "io" "net" "sync" "sync/atomic" "time" ) func newConnPair(bufSize int) (*pipeConn, *pipeConn) { b1 := bytes.NewBuffer(make([]byte, 0, bufSize)) b2 := bytes.NewBuffer(make([]byte, 0, bufSize)) var b1Mu, b2Mu sync.Mutex pc1 := &pipeConn{ cToS: b1, cToSMu: &b1Mu, sToC: b2, sToCMu: &b2Mu, } pc2 := &pipeConn{ cToS: b2, cToSMu: &b2Mu, sToC: b1, sToCMu: &b1Mu, } return pc1, pc2 } type pipeConn struct { cToS io.Writer sToC io.Reader // Mutexes used because readers and writers are not assumed to be // thread-safe. cToSMu, sToCMu *sync.Mutex closed uint32 } func (pc *pipeConn) isClosed() bool { return atomic.LoadUint32(&pc.closed) == 1 } func (pc *pipeConn) Read(b []byte) (n int, err error) { if pc.isClosed() { return 0, ErrClosed } pc.sToCMu.Lock() defer pc.sToCMu.Unlock() read, err := pc.sToC.Read(b) if err == io.EOF { return read, nil } return read, err } func (pc *pipeConn) Write(b []byte) (n int, err error) { if pc.isClosed() { return 0, ErrClosed } pc.cToSMu.Lock() defer pc.cToSMu.Unlock() return pc.cToS.Write(b) } // Close closes the connection. // // Any future calls to methods of this object will return ErrClosed. func (pc *pipeConn) Close() error { if atomic.CompareAndSwapUint32(&pc.closed, 0, 1) { // Succeeded. First call to close the connection. return nil } // Failed. Not the first call to attempt to close the connection. return ErrClosed } func (pc *pipeConn) LocalAddr() net.Addr { panic("implement me") } func (pc *pipeConn) RemoteAddr() net.Addr { return &net.TCPAddr{ IP: net.IPv4(127, 0, 0, 1), Port: 22, } } func (pc *pipeConn) SetDeadline(t time.Time) error { if pc.isClosed() { return ErrClosed } panic("implement me") } func (pc *pipeConn) SetReadDeadline(t time.Time) error { if pc.isClosed() { return ErrClosed } panic("implement me") } func (pc *pipeConn) SetWriteDeadline(t time.Time) error { if pc.isClosed() { return ErrClosed } panic("implement me") }
package pipeline import ( "context" "encoding/base64" "fmt" ) //Encode 는 in 에서 일반 텍스트를 입력받아 //"입력 문자열" => <base64 인코딩된 문자열>을 out 에 쓴다. func (w *Worker) Encode(ctx context.Context) { for { select { case <-ctx.Done(): return case val := <-w.in: w.out <- fmt.Sprintf("%s => %s", val, base64.StdEncoding.EncodeToString([]byte(val))) } } }
package timeformat import ( "strings" "time" ) var ( lm = []string{ "YYYY", "2006", "YY", "06", "MMMM", "January", "MMM", "Jan", "MM", "01", "M", "1", "DD", "02", "D", "2", "hh", "03", "HH", "15", "h", "3", "wwww", "Monday", "www", "Mon", "mm", "04", "m", "4", "ss", "05", "s", "5", "f", "0", "F", "9", "a", "pm", "A", "PM", "z", "MST", "-Z:Z:Z", "-07:00:00", "Z:Z:Z", "Z07:00:00", "-Z:Z", "-07:00", "Z:Z", "Z07:00", "-ZZZ", "-070000", "ZZZ", "Z070000", "-ZZ", "-0700", "ZZ", "Z0700", "-Z", "-07", "Z", "Z07", } replacer *strings.Replacer ) func init() { replacer = strings.NewReplacer(lm...) } // Time is wrapper around the default time.Time object which can be formatted // using the custom layout type Time struct { time.Time } // T returns a wrapper around the time.Time object which can be formatted // using the custom layout func T(t time.Time) Time { return Time{t} } // Format returns a textual representation of the time value formatted // according to the custom layout func (t Time) Format(s string) string { return t.Time.Format(replacer.Replace(s)) } // Layout returns the parsed layout which can be passed to the Format // method of time.Time func Layout(s string) string { return replacer.Replace(s) }
package main import ( "bufio" "fmt" "io" "os" ) func main() { //os.O_WRONLY | os.O_TRUNC:只写方式打开并且清空 //file, err := os.OpenFile("F:/go/src/golangStudy/file_opt/you.txt", os.O_WRONLY|os.O_TRUNC, 0666) //os.O_WRONLY | os.O_TRUNC:只写方式打开并且追加 //file, err := os.OpenFile("F:/go/src/golangStudy/file_opt/you.txt", os.O_WRONLY|os.O_APPEND, 0666) //os.O_WRONLY | os.O_TRUNC:读写方式打开并且追加 file, err := os.OpenFile("F:/go/src/golangStudy/file_opt/you.txt", os.O_RDWR|os.O_APPEND, 0666) if err != nil { fmt.Println(err) return } //及时关闭file句柄 defer file.Close() //读取原来内容并显示 reader := bufio.NewReader(file) for { //读到一个换行符就结束一次 str, err := reader.ReadString('\n') fmt.Printf(str) //io.EOF表示读到了文件的末尾 if err == io.EOF { break } } str := "bbbbbbbbbb\n" //写入时,使用带缓存的*Writer writer := bufio.NewWriter(file) for i := 0; i < 5; i++ { writer.WriteString(str) } //writer是带缓存,因此在调用WriteString时候内容是先写入到缓存,不落盘,需要执行writer.Flush()写入硬盘 writer.Flush() }
package aliyun import ( "os" "path" ) // inject neccessary AliIndex.class for aliyun function func (m* Manager) createJava8Function(dir string) error { home, err := os.UserHomeDir() if err != nil { return err } // TODO: config err = os.Link(path.Join(home, ".jfManager", "ali", "java8", "AliIndex.class") ,path.Join(dir, "jointfaas", "AliIndex.class")) if err != nil { return err } return nil }
package main import ( "os" "os/exec" "strings" "github.com/matti/fixer" ) func main() { prefixer := fixer.Fixer{ Writer: os.Stdout, PrefixFunc: func(s string) string { return "pinging " }, InfixFunc: func(s string) string { if len(s) > 25 { return "< " + s[:25] + " ... >" } return "< " + s + " >" }, SuffixFunc: func(s string) string { padding := "" if amount := 36 - len(s); amount > 0 { padding = strings.Repeat(" ", amount) } return padding + "ponging" }, } cmd := exec.Command("ping", "-c", "3", "google.com") cmd.Stdout = prefixer cmd.Run() }
package main import ( "net/http" "github.com/GoGroup/Movie-and-events/cinema/repository" "github.com/GoGroup/Movie-and-events/cinema/service" "github.com/GoGroup/Movie-and-events/cinev_park/http/handler" usrvim "github.com/GoGroup/Movie-and-events/hall/repository" urepim "github.com/GoGroup/Movie-and-events/hall/service" "github.com/GoGroup/Movie-and-events/model" schrep "github.com/GoGroup/Movie-and-events/schedule/repository" schser "github.com/GoGroup/Movie-and-events/schedule/service" mvrep "github.com/GoGroup/Movie-and-events/movie/repository" mvser "github.com/GoGroup/Movie-and-events/movie/service" evrep "github.com/GoGroup/Movie-and-events/event/repository" evser "github.com/GoGroup/Movie-and-events/event/service" bkrep "github.com/GoGroup/Movie-and-events/booking/repository" bkser "github.com/GoGroup/Movie-and-events/booking/service" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" "github.com/julienschmidt/httprouter" ) func main() { db, err := gorm.Open("postgres", "postgres://postgres:admin@localhost/MovieEvent?sslmode=disable") if err != nil { panic(err) } defer db.Close() db.AutoMigrate(&model.Hall{}) db.AutoMigrate(&model.Cinema{}) db.AutoMigrate(&model.Booking{}) db.AutoMigrate(&model.Schedule{}) db.AutoMigrate(&model.Moviem{}) db.AutoMigrate(&model.Session{}) db.AutoMigrate(&model.Event{}) db.AutoMigrate(&model.Role{}) db.AutoMigrate(&model.Role{ID: 1, Name: "USER"}) db.AutoMigrate(&model.Role{ID: 2, Name: "ADMIN"}) // tmpl := template.Must(template.ParseGlob("../view/template/*")) myRouter := httprouter.New() // csrfSignKey := []byte(rtoken.GenerateRandomID(32)) // userRepo := usrep.NewUserGormRepo(db) // userService := usser.NewUserService(userRepo) // sessionRepo := usrep.NewSessionGormRepo(db) // sessionService := usser.NewSessionService(sessionRepo) // roleRepo := usrep.NewRoleGormRepo(db) // roleService := usser.NewRoleService(roleRepo) scheduleRepo := schrep.NewScheduleGormRepo(db) scheduleService := schser.NewScheduleService(scheduleRepo) sheduleHandler := handler.NewScheduleHandler(scheduleService) HallRepo := usrvim.NewHallGormRepo(db) Hallsr := urepim.NewHallService(HallRepo) HallHandler := handler.NewHallHandler(Hallsr) CinemaRepo := repository.NewCinemaGormRepo(db) Cinemasr := service.NewCinemaService(CinemaRepo) CinemaHandler := handler.NewCinemaHandler(Cinemasr) MovieRepo := mvrep.NewMovieGormRepo(db) Moviesr := mvser.NewMovieService(MovieRepo) MovieHandler := handler.NewMovieHander(Moviesr) EventRepo := evrep.NewEventGormRepo(db) Eventsr := evser.NewEventService(EventRepo) EventHandler := handler.NewEventHandler(Eventsr) BookRepo := bkrep.NewBookingGormRepo(db) Booksr := bkser.NewBookingService(BookRepo) BookHandler := handler.NewBookingHandler(Booksr) // uh := handler.NewUserHandler(tmpl, userService, sessionService, roleService, csrfSignKey) // mh := handler.NewMenuHandler(tmpl, Cinemasr, Hallsr, scheduleService, Moviesr) // ah := handler.NewAdminHandler(tmpl, Cinemasr, Hallsr, scheduleService, Moviesr) myRouter.ServeFiles("/assets/*filepath", http.Dir("../view/assets")) // myRouter.GET("/adminCinemas", ah.AdminCinema) // myRouter.GET("/adminCinemas/adminSchedule/:hId", ah.AdminSchedule) // myRouter.GET("/adminCinemas/adminSchedule/:hId/delete/:sId", ah.AdminScheduleDelete) // myRouter.GET("/adminCinemas/adminSchedule/:hId/new/", ah.NewAdminSchedule) // myRouter.POST("/adminCinemas/adminSchedule/:hId/new/", ah.NewAdminSchedulePost) // myRouter.GET("/home", mh.Index) // myRouter.GET("/movies", mh.Movies) // myRouter.GET("/movie/:mId", mh.EachMovieHandler) // myRouter.GET("/theaters", mh.Theaters) // myRouter.GET("/theater/schedule/:cName/:cId", mh.TheaterSchedule) // myRouter.GET("/", uh.Login) // myRouter.GET("/login", uh.Login) // myRouter.GET("/signup", uh.SignUp) // myRouter.POST("/login", uh.Login) // myRouter.POST("/signup", uh.SignUp) myRouter.GET("/api/schedules", sheduleHandler.GetSchedules) myRouter.GET("/api/cinemaschedules/:id/:day", sheduleHandler.GetSchedulesCinemaDay) myRouter.GET("/api/hallschedules/:hid/:day", sheduleHandler.GetSchedulesHallDay) myRouter.GET("/api/schedule/:id", sheduleHandler.GetSingleSchedule) myRouter.DELETE("/api/schedule/:id", sheduleHandler.DeleteSchedule) myRouter.PUT("/api/schedule/:id", sheduleHandler.UpdateSchedule) myRouter.POST("/api/schedule", sheduleHandler.PostSchedule) myRouter.GET("/api/cinemas", CinemaHandler.GetCinemas) myRouter.POST("/api/cinema", CinemaHandler.PostCinema) myRouter.GET("/api/cinema/:id", CinemaHandler.GetSingleCinema) myRouter.GET("/api/hallcinema/:id", HallHandler.GetCinemaHalls) myRouter.GET("/api/halls", HallHandler.GetHalls) myRouter.GET("/api/hall/:id", HallHandler.GetSingleHall) myRouter.PUT("/api/hall/:id", HallHandler.PutHall) myRouter.DELETE("/api/hall/:id", HallHandler.DeleteHall) myRouter.POST("/api/hall", HallHandler.PostHall) myRouter.GET("/api/events", EventHandler.GetEvents) myRouter.GET("/api/event/:id", EventHandler.GetSingleEvent) myRouter.PUT("/api/event/:id", EventHandler.PutEvent) myRouter.DELETE("/api/event/:id", EventHandler.DeleteEvent) myRouter.POST("/api/event", EventHandler.PostEvent) myRouter.GET("/api/movies", MovieHandler.GetMovies) myRouter.POST("/api/movie", MovieHandler.PostMovie) myRouter.POST("/api/booking", BookHandler.PostBooking) myRouter.GET("/api/bookings/:id", BookHandler.GetBookings) http.ListenAndServe(":8080", myRouter) }
package main import "fmt" func main() { m := make(map[string]int) changeMe(m) fmt.Println(m["Shikamaru"]) // 10 } func changeMe(z map[string]int) { z["Shikamaru"] = 10 } /* Allocation with make Back to allocation. The built-in function make(T, args) serves a purpose different from new(T). It creates slices, maps, and channels only, and it returns an initialized (not zeroed) value of type T (not *T). The reason for the distinction is that these three types represent, under the covers, references to data structures that must be initialized before use. A slice, for example, is a three-item descriptor containing a pointer to the data (inside an array), the length, and the capacity, and until those items are initialized, the slice is nil. For slices, maps, and channels, make initializes the internal data structure and prepares the value for use. https://golang.org/doc/effective_go.html#allocation_make */ // 44