### Install githubv4 Go Package Source: https://github.com/shurcool/githubv4/blob/main/README.md Installs the githubv4 Go package using the go get command. This is the initial step to start using the library in your Go projects. ```sh go get github.com/shurcooL/githubv4 ``` -------------------------------- ### Execute GraphQL Mutations with githubv4 in Go Source: https://context7.com/shurcool/githubv4/llms.txt Demonstrates how to execute GraphQL mutations using the githubv4 Go package. It includes functions for adding and removing reactions to issues, defining mutation structs, and handling input parameters. The example requires a GITHUB_TOKEN environment variable for authentication. ```Go package main import ( "context" "fmt" "log" "os" "github.com/shurcooL/githubv4" "golang.org/x/oauth2" ) func addReaction(ctx context.Context, client *githubv4.Client, subjectID string) error { var mutation struct { AddReaction struct { Reaction struct { Content githubv4.ReactionContent } Subject struct { ID githubv4.ID } } `graphql:"addReaction(input: $input)"` } input := githubv4.AddReactionInput{ SubjectID: githubv4.ID(subjectID), Content: githubv4.ReactionContentThumbsUp, // THUMBS_UP emoji } err := client.Mutate(ctx, &mutation, input, nil) if err != nil { return err } fmt.Printf("Added %s reaction to %s\n", mutation.AddReaction.Reaction.Content, mutation.AddReaction.Subject.ID) return nil } func removeReaction(ctx context.Context, client *githubv4.Client, subjectID string) error { var mutation struct { RemoveReaction struct { Reaction struct { Content githubv4.ReactionContent } } } input := githubv4.RemoveReactionInput{ SubjectID: githubv4.ID(subjectID), Content: githubv4.ReactionContentThumbsUp, } return client.Mutate(ctx, &mutation, input, nil) } func main() { src := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")}, ) httpClient := oauth2.NewClient(context.Background(), src) client := githubv4.NewClient(httpClient) // Add a thumbs up reaction to an issue (use actual issue ID) err := addReaction(context.Background(), client, "MDU6SXNzdWUyMTc5NTQ0OTc=") if err != nil { log.Fatal(err) } // Output: // Added THUMBS_UP reaction to MDU6SXNzdWUyMTc5NTQ0OTc= } ``` -------------------------------- ### Use GitHub GraphQL Enums in Go Source: https://context7.com/shurcool/githubv4/llms.txt Demonstrates how to use GitHub GraphQL enum types as Go constants. This example filters issue reactions by a specific content type using the ReactionContent enum. ```go package main import ( "context" "fmt" "log" "os" "github.com/shurcooL/githubv4" "golang.org/x/oauth2" ) func main() { src := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")}, ) httpClient := oauth2.NewClient(context.Background(), src) client := githubv4.NewClient(httpClient) var query struct { Repository struct { Issue struct { Reactions struct { Nodes []struct { Content githubv4.ReactionContent User struct { Login string } } } `graphql:"reactions(first: 10, content: $content)"` } `graphql:"issue(number: 1)"` } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "owner": githubv4.String("octocat"), "name": githubv4.String("Hello-World"), "content": githubv4.ReactionContentThumbsUp, } err := client.Query(context.Background(), &query, variables) if err != nil { log.Fatal(err) } for _, r := range query.Repository.Issue.Reactions.Nodes { fmt.Printf("%s reacted with %s\n", r.User.Login, r.Content) } } ``` -------------------------------- ### Create a GitHub GraphQL Client Source: https://context7.com/shurcool/githubv4/llms.txt Initializes a new client for the public GitHub GraphQL API. It requires an authenticated http.Client, typically provided by the oauth2 package. ```go package main import ( "context" "fmt" "log" "os" "github.com/shurcooL/githubv4" "golang.org/x/oauth2" ) func main() { src := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")}, ) httpClient := oauth2.NewClient(context.Background(), src) client := githubv4.NewClient(httpClient) fmt.Println("GitHub GraphQL client created successfully") } ``` -------------------------------- ### Create a GitHub Enterprise Client Source: https://context7.com/shurcool/githubv4/llms.txt Initializes a client specifically for GitHub Enterprise instances. This requires providing the custom GraphQL endpoint URL. ```go package main import ( "context" "os" "github.com/shurcooL/githubv4" "golang.org/x/oauth2" ) func main() { src := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: os.Getenv("GITHUB_ENTERPRISE_TOKEN")}, ) httpClient := oauth2.NewClient(context.Background(), src) client := githubv4.NewEnterpriseClient( "https://github.mycompany.com/api/graphql", httpClient, ) _ = client } ``` -------------------------------- ### Pointer Helpers for Optional GraphQL Arguments in Go Source: https://context7.com/shurcool/githubv4/llms.txt Explains the use of `New*` helper functions in the githubv4 Go package to create pointers for optional GraphQL arguments. This is crucial for handling nullable parameters and implementing cursor-based pagination effectively. ```Go package main import ( "fmt" "time" "github.com/shurcooL/githubv4" ) func main() { // Create pointer to String (for optional cursor) cursor := githubv4.NewString(githubv4.String("Y3Vyc29yOjE5NTE4NDI1Ng==")) // Create pointer to Int (for optional limit) limit := githubv4.NewInt(githubv4.Int(50)) // Create pointer to Boolean archived := githubv4.NewBoolean(githubv4.Boolean(true)) // Create pointer to DateTime since := githubv4.NewDateTime(githubv4.DateTime{Time: time.Now()}) // Create pointer to ID nodeID := githubv4.NewID(githubv4.ID("MDU6SXNzdWUyMTc5NTQ0OTc=")) // Nil pointer for first page (no cursor) var noCursor *githubv4.String = nil // Use in variables for pagination variables := map[string]interface{}{ "after": noCursor, // First page "first": limit, "archived": archived, "since": since, "nodeId": nodeID, } // After first query, use cursor for next page variables["after"] = cursor fmt.Printf("Pagination variables: %+v\n", variables) } ``` -------------------------------- ### Execute Simple GraphQL Query with githubv4 Source: https://github.com/shurcool/githubv4/blob/main/README.md Shows how to execute a simple GraphQL query using the githubv4 client. It involves defining a Go struct that mirrors the expected JSON response structure and then passing a pointer to this struct to the client.Query method. ```Go import "context" import "fmt" var query struct { Viewer struct { Login githubv4.String CreatedAt githubv4.DateTime } } err := client.Query(context.Background(), &query, nil) if err != nil { // Handle error. } fmt.Println(" Login:", query.Viewer.Login) fmt.Println("CreatedAt:", query.Viewer.CreatedAt) ``` -------------------------------- ### Execute a Simple GraphQL Query Source: https://context7.com/shurcool/githubv4/llms.txt Demonstrates how to fetch data by defining a Go struct that mirrors the desired GraphQL schema fields. The response is automatically unmarshaled into the struct. ```go package main import ( "context" "fmt" "log" "os" "time" "github.com/shurcooL/githubv4" "golang.org/x/oauth2" ) func main() { src := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")}, ) httpClient := oauth2.NewClient(context.Background(), src) client := githubv4.NewClient(httpClient) var query struct { Viewer struct { Login string CreatedAt time.Time AvatarURL string `graphql:"avatarUrl(size: 72)"` } } err := client.Query(context.Background(), &query, nil) if err != nil { log.Fatal(err) } fmt.Println("Login:", query.Viewer.Login) fmt.Println("Created:", query.Viewer.CreatedAt) fmt.Println("Avatar:", query.Viewer.AvatarURL) } ``` -------------------------------- ### Authenticate GitHub GraphQL API v4 Client Source: https://github.com/shurcool/githubv4/blob/main/README.md Demonstrates how to authenticate the githubv4 client using an OAuth2 token. It shows setting up an http.Client with a static token source and then creating a new githubv4 client. For GitHub Enterprise, it shows how to use NewEnterpriseClient. ```Go import "golang.org/x/oauth2" import "context" import "os" func main() { ssrc := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")}, ) httpClient := oauth2.NewClient(context.Background(), src) client := githubv4.NewClient(httpClient) // Use client... } ``` ```Go import "golang.org/x/oauth2" import "context" import "os" func main() { client := githubv4.NewEnterpriseClient(os.Getenv("GITHUB_ENDPOINT"), httpClient) // Use client... } ``` -------------------------------- ### Query with Variables Source: https://context7.com/shurcool/githubv4/llms.txt Shows how to pass dynamic arguments to a query using a map of variables. Variables must be mapped to the library's specific scalar types. ```go package main import ( "context" "fmt" "log" "os" "github.com/shurcooL/githubv4" "golang.org/x/oauth2" ) func fetchRepoDescription(ctx context.Context, client *githubv4.Client, owner, name string) (string, error) { var query struct { Repository struct { Description string URL string StargazerCount int } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "owner": githubv4.String(owner), "name": githubv4.String(name), } err := client.Query(ctx, &query, variables) if err != nil { return "", err } return query.Repository.Description, nil } func main() { src := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")}, ) httpClient := oauth2.NewClient(context.Background(), src) client := githubv4.NewClient(httpClient) description, err := fetchRepoDescription(context.Background(), client, "octocat", "Hello-World") if err != nil { log.Fatal(err) } fmt.Println("Description:", description) } ``` -------------------------------- ### Perform AddReaction Mutation Source: https://github.com/shurcool/githubv4/blob/main/README.md Demonstrates how to define a mutation structure and execute it using the client.Mutate method. It requires a pre-defined input struct and handles the response by mapping it to the provided Go structure. ```GraphQL mutation($input: AddReactionInput!) { addReaction(input: $input) { reaction { content } subject { id } } } variables { "input": { "subjectId": "MDU6SXNzdWUyMTc5NTQ0OTc=", "content": "HOORAY" } } ``` ```Go var m struct { AddReaction struct { Reaction struct { Content githubv4.ReactionContent } Subject struct { ID githubv4.ID } } `graphql:"addReaction(input: $input)"` } input := githubv4.AddReactionInput{ SubjectID: targetIssue.ID, Content: githubv4.ReactionContentHooray, } err := client.Mutate(context.Background(), &m, input, nil) if err != nil { // Handle error. } fmt.Printf("Added a %v reaction to subject with ID %#v!\n", m.AddReaction.Reaction.Content, m.AddReaction.Subject.ID) ``` -------------------------------- ### Querying Repository with Dynamic Variables in Go Source: https://github.com/shurcool/githubv4/blob/main/README.md Demonstrates how to query a repository's description using dynamic variables in Go. It defines a struct with placeholder variables in the `graphql` tag and a corresponding map for variable values. This approach is used when arguments are not known until runtime. ```Go // fetchRepoDescription fetches description of repo with owner and name. func fetchRepoDescription(ctx context.Context, owner, name string) (string, error) { var q struct { Repository struct { Description string } `graphql:"repository(owner: $owner, name: $name)"` } variables := map[string]interface{}{ "owner": githubv4.String(owner), "name": githubv4.String(name), } err := client.Query(ctx, &q, variables) return q.Repository.Description, err } ``` -------------------------------- ### Implementing Pagination for Lists in Go Source: https://github.com/shurcool/githubv4/blob/main/README.md Provides a Go implementation for paginating through lists of data, such as comments on an issue. It demonstrates how to use `PageInfo` to check for the next page and update the cursor for subsequent queries within a loop. This allows fetching all items beyond the initial page limit. ```Go type comment struct { Body string Author struct { Login string AvatarURL string `graphql:"avatarUrl(size: 72)"` } ViewerCanReact bool } var q struct { Repository struct { Issue struct { Comments struct { Nodes []comment PageInfo struct { EndCursor githubv4.String HasNextPage bool } } `graphql:"comments(first: 100, after: $commentsCursor)"` } `graphql:"issue(number: $issueNumber)"` } `graphql:"repository(owner: $repositoryOwner, name: $repositoryName)"` } variables := map[string]interface{}{ "repositoryOwner": githubv4.String(owner), "repositoryName": githubv4.String(name), "issueNumber": githubv4.Int(issue), "commentsCursor": (*githubv4.String)(nil), // Null after argument to get first page. } // Get comments from all pages. var allComments []comment for { err := client.Query(ctx, &q, variables) if err != nil { return err } allComments = append(allComments, q.Repository.Issue.Comments.Nodes...) if !q.Repository.Issue.Comments.PageInfo.HasNextPage { break } variables["commentsCursor"] = githubv4.NewString(q.Repository.Issue.Comments.PageInfo.EndCursor) } ``` -------------------------------- ### Querying Repository with Static Arguments in Go Source: https://github.com/shurcool/githubv4/blob/main/README.md Defines a Go struct to represent a GraphQL query for a repository with static owner and name arguments. It demonstrates how to use the `graphql` struct field tag for direct mapping. This method is suitable when arguments are known at compile time. ```Go var q struct { Repository struct { Description string } `graphql:"repository(owner: \"octocat\", name: \"Hello-World\")"` } err := client.Query(context.Background(), &q, nil) if err != nil { // Handle error. } fmt.Println(q.Repository.Description) ``` -------------------------------- ### Using GitHub GraphQL Scalar Types in Go Source: https://context7.com/shurcool/githubv4/llms.txt Illustrates how to use the Go types provided by the githubv4 package for GitHub GraphQL scalars. These types ensure compatibility when sending variables to the GraphQL schema, covering strings, integers, booleans, IDs, dates, and more. ```Go package main import ( "fmt" "time" "github.com/shurcooL/githubv4" ) func main() { // String types owner := githubv4.String("octocat") name := githubv4.String("Hello-World") // Integer types issueNumber := githubv4.Int(42) first := githubv4.Int(100) // Boolean types includeArchived := githubv4.Boolean(false) // ID types (Base64 encoded) nodeID := githubv4.ID("MDU6SXNzdWUyMTc5NTQ0OTc=") // DateTime with time.Time since := githubv4.DateTime{Time: time.Now().AddDate(0, -1, 0)} // Git object ID (SHA) commitSHA := githubv4.GitObjectID("912ec1990bd09f8fc128c3fa6b59105085aabc03") // Git ref name branch := githubv4.GitRefname("refs/heads/main") // HTML content bio := githubv4.HTML("
Hello, World!
") // Use in variables map variables := map[string]interface{}{ "owner": owner, "name": name, "issueNumber": issueNumber, "first": first, "includeArchived": includeArchived, "nodeID": nodeID, "since": since, "commitSHA": commitSHA, "branch": branch, "bio": bio, } fmt.Printf("Variables: %+v\n", variables) } ``` -------------------------------- ### Execute Complex Nested GraphQL Queries Source: https://context7.com/shurcool/githubv4/llms.txt Shows how to build complex, deeply nested queries by defining Go structs that mirror the GraphQL schema. Includes handling of nested relationships like repository, issue, comments, and rate limit information. ```go package main import ( "context" "encoding/json" "fmt" "log" "os" "github.com/shurcooL/githubv4" "golang.org/x/oauth2" ) type Actor struct { Login githubv4.String AvatarURL githubv4.URI `graphql:"avatarUrl(size: 72)"` URL githubv4.URI } func main() { src := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")}, ) httpClient := oauth2.NewClient(context.Background(), src) client := githubv4.NewClient(httpClient) var query struct { Repository struct { DatabaseID githubv4.Int URL githubv4.URI Issue struct { Author Actor PublishedAt githubv4.DateTime LastEditedAt *githubv4.DateTime Editor *Actor Body githubv4.String ReactionGroups []struct { Content githubv4.ReactionContent Users struct { TotalCount githubv4.Int } ViewerHasReacted githubv4.Boolean } Comments struct { Nodes []struct { Body githubv4.String Author struct { Login githubv4.String } } PageInfo struct { EndCursor githubv4.String HasNextPage githubv4.Boolean } } `graphql:"comments(first: $commentsFirst)"` } `graphql:"issue(number: $issueNumber)"` } `graphql:"repository(owner: $owner, name: $name)"` Viewer struct { Login githubv4.String CreatedAt githubv4.DateTime } RateLimit struct { Cost githubv4.Int Limit githubv4.Int Remaining githubv4.Int ResetAt githubv4.DateTime } } variables := map[string]interface{}{ "owner": githubv4.String("octocat"), "name": githubv4.String("Hello-World"), "issueNumber": githubv4.Int(1), "commentsFirst": githubv4.Int(10), } err := client.Query(context.Background(), &query, variables) if err != nil { log.Fatal(err) } output, _ := json.MarshalIndent(query, "", " ") fmt.Println(string(output)) } ``` -------------------------------- ### Implementing Cursor-Based Pagination with PageInfo Source: https://context7.com/shurcool/githubv4/llms.txt This snippet shows how to fetch paginated data from the GitHub API by iterating through pages using the PageInfo object. It updates the 'cursor' variable with the 'EndCursor' value until 'HasNextPage' is false. ```go variables := map[string]interface{}{ "owner": githubv4.String(owner), "name": githubv4.String(repo), "issueNumber": githubv4.Int(issueNum), "cursor": (*githubv4.String)(nil), } for { err := client.Query(ctx, &query, variables) if err != nil { return nil, err } allComments = append(allComments, query.Repository.Issue.Comments.Nodes...) if !query.Repository.Issue.Comments.PageInfo.HasNextPage { break } variables["cursor"] = githubv4.NewString(query.Repository.Issue.Comments.PageInfo.EndCursor) } ``` -------------------------------- ### Map GraphQL Scalar Types to Go Types Source: https://github.com/shurcool/githubv4/blob/main/README.md Illustrates how to map GitHub GraphQL scalar types (String, DateTime, Boolean, HTML, URI) to corresponding Go types provided by the githubv4 package. It also shows how to use standard Go types or custom types that implement json.Unmarshaler for convenience. ```Go import "context" import "time" var query struct { Viewer struct { Login githubv4.String CreatedAt githubv4.DateTime IsBountyHunter githubv4.Boolean BioHTML githubv4.HTML WebsiteURL githubv4.URI } } // Call client.Query() and use results in query... ``` ```Go import "context" import "time" var query struct { Viewer struct { Login string // E.g., "gopher". CreatedAt time.Time // E.g., time.Date(2017, 5, 26, 21, 17, 14, 0, time.UTC). IsBountyHunter bool // E.g., true. BioHTML string // E.g., `I am learning GraphQL!`. WebsiteURL string // E.g., "https://golang.org". } } // Call client.Query() and use results in query... ``` ```Go import "context" import "html/template" type MyBoolean bool var query struct { Viewer struct { Login string // E.g., "gopher". CreatedAt string // E.g., "2017-05-26T21:17:14Z". IsBountyHunter MyBoolean // E.g., MyBoolean(true). BioHTML template.HTML // E.g., template.HTML(`I am learning GraphQL!`). WebsiteURL template.URL // E.g., template.URL("https://golang.org"). } } // Call client.Query() and use results in query... ``` -------------------------------- ### Using Inline Fragments for Conditional Data in Go Source: https://github.com/shurcool/githubv4/blob/main/README.md Shows how to use inline fragments in Go GraphQL queries to conditionally fetch data based on the type of the returned object. It illustrates defining fragments directly in the struct tag or by defining separate fragment structs for clarity. This is useful when a field can return different types. ```Go var q struct { RepositoryOwner struct { Login string Organization struct { Description string } `graphql:"... on Organization"` User struct { Bio string } `graphql:"... on User"` } `graphql:"repositoryOwner(login: \"github\")"` } err := client.Query(context.Background(), &q, nil) if err != nil { // Handle error. } fmt.Println(q.RepositoryOwner.Login) fmt.Println(q.RepositoryOwner.Description) fmt.Println(q.RepositoryOwner.Bio) ``` ```Go type ( OrganizationFragment struct { Description string } UserFragment struct { Bio string } ) var q struct { RepositoryOwner struct { Login string OrganizationFragment `graphql:"... on Organization"` UserFragment `graphql:"... on User"` } `graphql:"repositoryOwner(login: \"github\")"` } err := client.Query(context.Background(), &q, nil) if err != nil { // Handle error. } fmt.Println(q.RepositoryOwner.Login) fmt.Println(q.RepositoryOwner.Description) fmt.Println(q.RepositoryOwner.Bio) ``` -------------------------------- ### Querying Polymorphic Types with Inline Fragments Source: https://context7.com/shurcool/githubv4/llms.txt This snippet demonstrates how to use inline fragments in Go structs to query fields specific to interface implementations. It uses the graphql tag syntax to map fields to specific types like Organization or User. ```go var query struct { RepositoryOwner struct { Login string Organization struct { Description string MembersCount int `graphql:"membersWithRole { totalCount }"` } `graphql:"... on Organization"` User struct { Bio string Company string Followers struct { TotalCount int } } `graphql:"... on User"` } `graphql:"repositoryOwner(login: \"github\")"` } err := client.Query(context.Background(), &query, nil) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.