Documentation
¶
Overview ¶
Package iserv provides a lightweight, concurrency-safe Go 1.26 SDK for interacting with IServ school portals.
It supports web form and OIDC handoff authentication, subpath-mounted portals, automatic single-flight session renewal, structured logging via github.com/TallSmaN/pnmd (NewLogger), and eight domain services:
- ProfileService for user profile metadata and avatars
- EmailService for mail folders, paginated listings, lazy iterators, and full messages
- FilesService for RFC 4918 WebDAV directory browsing and streaming downloads
- GroupsService for school groups, classes, and membership rosters
- CalendarService for calendar sources and events (JSON feeds and CalDAV fallback)
- TasksService for student exercises (Aufgaben), submissions, and attachments
- NotificationsService for portal alerts and read-state management
- DirectoryService for user lookup across autocomplete, CardDAV, and addressbook routes
Concurrency Safety ¶
A Client and all of its attached services are safe for concurrent use by multiple goroutines. Concurrent lazy logins and session refreshes are coalesced via golang.org/x/sync/singleflight so only a single upstream authentication request executes at a time.
Error Handling ¶
All methods return wrapped errors compatible with errors.Is against the package sentinel errors (ErrInvalidDomain, ErrValidation, ErrInvalidCredentials, ErrUnauthorized, ErrForbidden, ErrNotFound, ErrUpstreamUnavailable, ErrUpstreamProtocol, ErrResponseTooLarge) and with errors.AsType against *Error.
Quick Start ¶
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
client, err := iserv.New(ctx, "school.iserv.de", "max.mustermann", "secret")
if err != nil {
log.Fatal(err)
}
defer client.Close(context.Background())
profile, err := client.Profile.Get(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println(profile.FullName, profile.Email)
Index ¶
- Variables
- func ErrorCode(err error) string
- func NewLogger(w io.Writer, level slog.Level) *slog.Logger
- type Address
- type Attachment
- type Avatar
- type CalendarEvent
- type CalendarEventsOptions
- type CalendarService
- type CalendarSource
- type Client
- type DirectoryService
- type DirectoryUser
- type EmailDetail
- type EmailListOptions
- type EmailPage
- type EmailService
- func (s *EmailService) All(ctx context.Context, opts EmailListOptions) iter.Seq2[EmailSummary, error]
- func (s *EmailService) Folders(ctx context.Context) ([]Folder, error)
- func (s *EmailService) Get(ctx context.Context, folder, uid string) (*EmailDetail, error)
- func (s *EmailService) List(ctx context.Context, opts EmailListOptions) (*EmailPage, error)
- type EmailSummary
- type Error
- type FileDownload
- type FileEntry
- type FilesService
- type Folder
- type Group
- type GroupDetail
- type GroupMember
- type GroupsService
- type Notification
- type NotificationsService
- type Option
- type PageMeta
- type Profile
- type ProfileService
- type TaskAttachment
- type TaskDetail
- type TaskStatus
- type TaskSummary
- type TasksService
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrValidation indicates invalid caller-supplied input parameters. ErrValidation = errors.New("iserv: validation error") // ErrInvalidDomain indicates a malformed school domain or blocked SSRF target. ErrInvalidDomain = errors.New("iserv: invalid school domain") ErrUnauthorized = errors.New("iserv: unauthorized") // ErrInvalidCredentials indicates rejected login credentials. ErrInvalidCredentials = errors.New("iserv: invalid credentials") // ErrForbidden indicates the authenticated user lacks access to the resource. ErrForbidden = errors.New("iserv: forbidden") // ErrNotFound indicates the requested resource does not exist on IServ. ErrNotFound = errors.New("iserv: not found") ErrUpstreamUnavailable = errors.New("iserv: upstream unavailable") // ErrUpstreamProtocol indicates malformed or unexpected upstream payloads. ErrUpstreamProtocol = errors.New("iserv: upstream protocol error") // ErrResponseTooLarge indicates an upstream response exceeded MaxBodyBytes. ErrResponseTooLarge = errors.New("iserv: response body too large") )
Sentinel errors returned by the SDK for idiomatic errors.Is checks.
Functions ¶
func ErrorCode ¶
ErrorCode extracts the machine-readable error code from err, or returns "" if err does not contain an *Error.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/IServify/iserv-go"
)
func main() {
_, err := iserv.NewUnauthenticated("http://localhost", "alice", "secret")
if errors.Is(err, iserv.ErrInvalidDomain) {
fmt.Println("code:", iserv.ErrorCode(err))
}
}
Output: code: insecure_scheme
func NewLogger ¶
NewLogger creates a concurrency-safe structured *slog.Logger backed by github.com/TallSmaN/pnmd. Pass it to WithLogger to enable formatted SDK logs.
Types ¶
type Attachment ¶
type Attachment struct {
ID string `json:"id,omitempty"`
Filename string `json:"filename"`
ContentType string `json:"content_type,omitempty"`
Size int64 `json:"size,omitempty"`
}
Attachment describes a file attached to an email message.
type CalendarEvent ¶
type CalendarEvent struct {
ID string `json:"id"`
CalendarID string `json:"calendar_id,omitempty"`
Title string `json:"title"`
Description string `json:"description,omitempty"`
Location string `json:"location,omitempty"`
Start time.Time `json:"start,omitzero"`
End time.Time `json:"end,omitzero"`
AllDay bool `json:"all_day"`
Categories []string `json:"categories,omitempty"`
}
CalendarEvent represents a scheduled appointment or event on an IServ calendar.
type CalendarEventsOptions ¶
CalendarEventsOptions filters calendar events by date window and optional source ID.
type CalendarService ¶
type CalendarService struct {
// contains filtered or unexported fields
}
CalendarService accesses calendar sources and scheduled events across IServ JSON feeds, per-source endpoints, and CalDAV fallback.
func (*CalendarService) Events ¶
func (s *CalendarService) Events(ctx context.Context, opts CalendarEventsOptions) ([]CalendarEvent, error)
Events returns chronologically sorted calendar events within opts.Start..opts.End. Zero Start defaults to today UTC; zero End defaults to Start + 30 days. Date ranges exceeding 366 days are rejected with ErrValidation.
func (*CalendarService) List ¶
func (s *CalendarService) List(ctx context.Context) ([]CalendarSource, error)
List returns all calendar sources visible to the authenticated user.
type CalendarSource ¶
type CalendarSource struct {
ID string `json:"id"`
Name string `json:"name"`
Color string `json:"color,omitempty"`
Type string `json:"type,omitempty"`
CalDAVPath string `json:"caldav_path,omitempty"`
ReadOnly bool `json:"read_only"`
}
CalendarSource represents a calendar feed available to the user.
type Client ¶
type Client struct {
Profile *ProfileService
Email *EmailService
Files *FilesService
Groups *GroupsService
Calendar *CalendarService
Tasks *TasksService
Notifications *NotificationsService
Directory *DirectoryService
// contains filtered or unexported fields
}
Client is a concurrency-safe IServ SDK client exposing eight domain services. A Client must not be copied after creation.
func New ¶
func New(ctx context.Context, schoolDomain, username, password string, opts ...Option) (*Client, error)
New validates credentials, constructs a Client, and authenticates immediately.
Example ¶
ctx := context.Background()
client, err := iserv.New(
ctx,
"school.example.de",
"alice",
"secret",
iserv.WithHTTPTransport(handlerTransport(newMockIServMux("", nil))),
)
if err != nil {
fmt.Println("login error:", err)
return
}
defer func() { _ = client.Close(ctx) }()
profile, err := client.Profile.Get(ctx)
if err != nil {
fmt.Println("profile error:", err)
return
}
fmt.Printf("%s <%s>\n", profile.FullName, profile.Email)
Output: Alice Example <alice@school.example>
func NewUnauthenticated ¶
NewUnauthenticated validates credentials and initializes all services without performing a network login.
func (*Client) BaseURL ¶
BaseURL returns the normalized school base URL including any subpath mount prefix.
func (*Client) Close ¶
Close terminates the active IServ session by calling Client.Logout.
type DirectoryService ¶
type DirectoryService struct {
// contains filtered or unexported fields
}
DirectoryService searches the school user directory across IServ autocomplete JSON APIs, CardDAV, and HTML addressbook fallbacks.
func (*DirectoryService) SearchUsers ¶
func (s *DirectoryService) SearchUsers(ctx context.Context, query string) ([]DirectoryUser, error)
SearchUsers finds IServ users matching query.
type DirectoryUser ¶
type DirectoryUser struct {
Account string `json:"account"`
FullName string `json:"full_name"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
Email string `json:"email,omitempty"`
Role string `json:"role,omitempty"`
AvatarURL string `json:"avatar_url,omitempty"`
Department string `json:"department,omitempty"`
Groups []string `json:"groups,omitempty"`
}
DirectoryUser represents a school directory user returned by IServ addressbook or user search.
type EmailDetail ¶
type EmailDetail struct {
EmailSummary
CC []Address `json:"cc,omitempty"`
TextBody string `json:"text_body,omitempty"`
HTMLBody string `json:"html_body,omitempty"`
Attachments []Attachment `json:"attachments,omitempty"`
}
EmailDetail holds full email content including body and attachment metadata.
type EmailListOptions ¶
EmailListOptions specifies folder, pagination, and sorting options for listing emails.
type EmailPage ¶
type EmailPage struct {
Items []EmailSummary `json:"items"`
Meta PageMeta `json:"meta"`
}
EmailPage wraps a page of email summaries and pagination metadata.
type EmailService ¶
type EmailService struct {
// contains filtered or unexported fields
}
EmailService accesses mail folders and messages in IServ webmail, supporting both modern /iserv/mail/api/v2 and legacy /iserv/mail/api endpoints.
func (*EmailService) All ¶
func (s *EmailService) All(ctx context.Context, opts EmailListOptions) iter.Seq2[EmailSummary, error]
All returns a lazy iter.Seq2 iterator over all emails matching opts across consecutive pages.
Example ¶
ctx := context.Background()
client, err := iserv.New(
ctx,
"school.example.de",
"alice",
"secret",
iserv.WithHTTPTransport(handlerTransport(newMockIServMux("", nil))),
)
if err != nil {
fmt.Println("login error:", err)
return
}
defer func() { _ = client.Close(ctx) }()
for msg, err := range client.Email.All(ctx, iserv.EmailListOptions{Folder: "INBOX", Limit: 10}) {
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(msg.UID, msg.Subject)
}
Output: 101 Welcome 102 Schedule
func (*EmailService) Folders ¶
func (s *EmailService) Folders(ctx context.Context) ([]Folder, error)
Folders lists all mail folders available to the authenticated user.
func (*EmailService) Get ¶
func (s *EmailService) Get(ctx context.Context, folder, uid string) (*EmailDetail, error)
Get retrieves full headers, text/HTML body, and attachment metadata for a single message.
func (*EmailService) List ¶
func (s *EmailService) List(ctx context.Context, opts EmailListOptions) (*EmailPage, error)
List retrieves a paginated list of email summaries from a folder (defaults to "INBOX").
type EmailSummary ¶
type EmailSummary struct {
UID string `json:"uid"`
Folder string `json:"folder"`
Subject string `json:"subject"`
From Address `json:"from"`
To []Address `json:"to,omitempty"`
Date time.Time `json:"date,omitzero"`
Seen bool `json:"seen"`
Flagged bool `json:"flagged"`
HasAttachments bool `json:"has_attachments"`
Size int64 `json:"size,omitempty"`
}
EmailSummary holds metadata for an email in a mailbox listing.
type Error ¶
type Error struct {
// Err is the canonical package sentinel error category.
Err error
// Cause is the optional underlying transport, parsing, or stdlib error.
Cause error
// Op identifies the SDK operation that failed (e.g., "auth.login").
Op string
// Code is a stable machine-readable error code (e.g., "session_expired").
Code string
// Message is a human-readable diagnostic summary without sensitive data.
Message string
// StatusCode is the upstream HTTP status code when applicable (0 otherwise).
StatusCode int
// Details holds optional safe, non-sensitive metadata (e.g., field name, URL).
Details map[string]string
}
Error represents a structured error returned by SDK operations. It wraps a canonical sentinel error (and optionally an underlying cause) so callers can inspect errors using errors.Is and errors.AsType.
type FileDownload ¶
type FileDownload struct {
Body io.ReadCloser `json:"-"`
FileName string `json:"file_name"`
ContentType string `json:"content_type"`
Size int64 `json:"size"`
}
FileDownload represents a live downloadable file stream from IServ WebDAV. Callers must close Body when finished reading.
type FileEntry ¶
type FileEntry struct {
Name string `json:"name"`
Path string `json:"path"`
IsDir bool `json:"is_dir"`
Size int64 `json:"size"`
ContentType string `json:"content_type,omitempty"`
ModifiedAt *time.Time `json:"modified_at,omitempty"`
ETag string `json:"etag,omitempty"`
}
FileEntry represents a file or directory in IServ WebDAV storage.
type FilesService ¶
type FilesService struct {
// contains filtered or unexported fields
}
FilesService accesses user and group files via IServ WebDAV.
func (*FilesService) Download ¶
func (s *FilesService) Download(ctx context.Context, filePath string) (*FileDownload, error)
Download opens a live stream for downloading the file at filePath. Callers must close the returned FileDownload.Body when finished.
func (*FilesService) DownloadTo ¶
DownloadTo streams the remote file at filePath directly into w without buffering the entire file in memory, returning the number of bytes written.
func (*FilesService) List ¶
List returns the sorted files and subdirectories at dirPath (defaults to "/"). Directory traversal segments ("..") and null bytes are rejected with ErrValidation.
type Folder ¶
type Folder struct {
Path string `json:"path"`
Name string `json:"name"`
UnreadCount int `json:"unread_count"`
TotalCount int `json:"total_count"`
Flags []string `json:"flags,omitempty"`
}
Folder represents an IServ mail folder (for example, INBOX, Sent, or Drafts).
type Group ¶
type Group struct {
ID string `json:"id"`
Name string `json:"name"`
Account string `json:"account,omitempty"`
Description string `json:"description,omitempty"`
Owner string `json:"owner,omitempty"`
FilesPath string `json:"files_path,omitempty"`
MemberCount int `json:"member_count,omitempty"`
}
Group represents an IServ school group, class, or course.
type GroupDetail ¶
type GroupDetail struct {
Group
Members []GroupMember `json:"members,omitempty"`
}
GroupDetail extends Group with its membership roster.
type GroupMember ¶
type GroupMember struct {
Username string `json:"username,omitempty"`
FullName string `json:"full_name,omitempty"`
Email string `json:"email,omitempty"`
Role string `json:"role,omitempty"`
}
GroupMember represents a member belonging to an IServ group.
type GroupsService ¶
type GroupsService struct {
// contains filtered or unexported fields
}
GroupsService accesses school groups, classes, and membership rosters.
func (*GroupsService) Get ¶
func (s *GroupsService) Get(ctx context.Context, rawID string) (*GroupDetail, error)
Get retrieves metadata and the membership roster for the specified group ID.
type Notification ¶
type Notification struct {
ID string `json:"id"`
Module string `json:"module,omitempty"`
Title string `json:"title"`
Message string `json:"message,omitempty"`
URL string `json:"url,omitempty"`
CreatedAt time.Time `json:"created_at,omitzero"`
Read bool `json:"read"`
}
Notification represents a portal alert or activity item in IServ.
type NotificationsService ¶
type NotificationsService struct {
// contains filtered or unexported fields
}
NotificationsService accesses portal alerts and notification read states.
func (*NotificationsService) List ¶
func (s *NotificationsService) List(ctx context.Context) ([]Notification, error)
List retrieves the user's notifications from IServ JSON routes, falling back to the /iserv/notification HTML page when JSON endpoints are unavailable.
func (*NotificationsService) MarkAllRead ¶
func (s *NotificationsService) MarkAllRead(ctx context.Context) error
MarkAllRead marks all notifications for the current user as read.
type Option ¶
type Option func(*clientConfig) error
Option customizes a Client constructed by New or NewUnauthenticated.
func WithAllowInsecureHTTP ¶
WithAllowInsecureHTTP enables http:// and localhost/IP school domains for development and testing.
func WithAutoReauth ¶
WithAutoReauth controls whether the client automatically re-authenticates once when a session expires.
func WithHTTPTransport ¶
func WithHTTPTransport(rt http.RoundTripper) Option
WithHTTPTransport injects a custom http.RoundTripper (proxy, custom TLS, instrumentation, or test mock).
func WithLogger ¶
WithLogger attaches a structured *slog.Logger (for example, built via NewLogger). Passwords and cookie values are never logged. Passing nil resets to slog.DiscardHandler.
func WithMaxBodyBytes ¶
WithMaxBodyBytes configures the maximum buffered response size read from IServ endpoints.
func WithTimeout ¶
WithTimeout configures the upstream HTTP timeout per request.
func WithUserAgent ¶
WithUserAgent overrides the User-Agent header sent to IServ endpoints.
type PageMeta ¶
type PageMeta struct {
Limit int `json:"limit"`
Offset int `json:"offset"`
Total int `json:"total"`
HasMore bool `json:"has_more"`
}
PageMeta describes paginated listing metadata.
type Profile ¶
type Profile struct {
Username string `json:"username"`
FullName string `json:"full_name,omitempty"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
Email string `json:"email,omitempty"`
SchoolDomain string `json:"school_domain"`
AvatarURL string `json:"avatar_url,omitempty"`
Groups []string `json:"groups,omitempty"`
Attributes map[string]string `json:"attributes,omitempty"`
}
Profile represents a user's IServ account profile.
type ProfileService ¶
type ProfileService struct {
// contains filtered or unexported fields
}
ProfileService accesses the authenticated user's profile metadata and avatar.
type TaskAttachment ¶
TaskAttachment describes a downloadable file attached to an exercise.
type TaskDetail ¶
type TaskDetail struct {
TaskSummary
Description string `json:"description,omitempty"`
Author string `json:"author,omitempty"`
Submission string `json:"submission,omitempty"`
Feedback string `json:"feedback,omitempty"`
Attachments []TaskAttachment `json:"attachments,omitempty"`
}
TaskDetail extends TaskSummary with full description, submission, feedback, and attachments.
type TaskStatus ¶
type TaskStatus string
TaskStatus filters IServ exercises by completion status.
const ( // TaskStatusCurrent lists currently active exercises. TaskStatusCurrent TaskStatus = "current" // TaskStatusPast lists archived or past exercises. TaskStatusPast TaskStatus = "past" // TaskStatusAll lists both current and past exercises merged without duplicates. TaskStatusAll TaskStatus = "all" )
type TaskSummary ¶
type TaskSummary struct {
ID string `json:"id"`
Title string `json:"title"`
StartDate string `json:"start_date,omitempty"`
DueDate string `json:"due_date,omitempty"`
Tags []string `json:"tags,omitempty"`
Done bool `json:"done"`
Reviewed bool `json:"reviewed"`
Overdue bool `json:"overdue"`
URL string `json:"url,omitempty"`
}
TaskSummary represents an assignment row in the IServ exercise overview.
type TasksService ¶
type TasksService struct {
// contains filtered or unexported fields
}
TasksService accesses student exercises and assignments (Aufgaben).
func (*TasksService) Get ¶
func (s *TasksService) Get(ctx context.Context, rawID string) (*TaskDetail, error)
Get retrieves full details, description, submission, feedback, and attachments for an exercise ID.
func (*TasksService) List ¶
func (s *TasksService) List(ctx context.Context, rawStatus TaskStatus) ([]TaskSummary, error)
List retrieves assignments filtered by status (TaskStatusCurrent, TaskStatusPast, or TaskStatusAll). Empty status defaults to TaskStatusCurrent. When TaskStatusAll is requested, current and past task pages are fetched concurrently.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
|
|
|
internal
|
|
|
credentials
Package credentials validates and normalizes IServ school connection details with SSRF hostname guards and secret redaction for formatting and logging.
|
Package credentials validates and normalizes IServ school connection details with SSRF hostname guards and secret redaction for formatting and logging. |
|
dav
Package dav integrates IServ RFC 4918 WebDAV, RFC 4791 CalDAV/iCal, and RFC 6352 CardDAV/vCard endpoints using github.com/emersion/go-webdav, go-ical, and go-vcard with XXE and bounded-body hardening.
|
Package dav integrates IServ RFC 4918 WebDAV, RFC 4791 CalDAV/iCal, and RFC 6352 CardDAV/vCard endpoints using github.com/emersion/go-webdav, go-ical, and go-vcard with XXE and bounded-body hardening. |
|
session
Package session manages tuned HTTP transport, strict host-boundary redirect validation, IServ form/OIDC authentication handoffs, and authenticated requests.
|
Package session manages tuned HTTP transport, strict host-boundary redirect validation, IServ form/OIDC authentication handoffs, and authenticated requests. |